Definition Of Comparator Interface

Definition Of Comparator Interface

Definition Of Comparator Interface ~ First of all, before reading this post you should understand what is an interface in craftingez6-coding.

You can found comparator interface in java.util.package and it contains 2 methods. Thus 2 of those methods are : .compare(obj1, obj2) and equals(Object element)

compare() method

public int compare(object1, object2)

Java Comparator Example (non-generic style)

Thus for this example I’ve created 2 class of sorting elements in the base of age and name. Due to the sake of simplicity of this article i’ve only created 2 :

  1. Age Comparator
  2. Name Comparator

Continue reading Definition Of Comparator Interface

What is a Comparable Interface?

What is a Comparable Interface?

What is a comparable interface – Coders can also order objects using java comparable interface. And rather than any type of class for that object. As a result, java uses user-defined class for this interface.

You can find java comparable interface inside the java.lang package since it is located inside that package. Therefore it contains only 1 method which seems like to be CompareTo(objects). Furthermore the interface provides single sorting element on a single data member only. So For an example it may be rollno, name, age or anything else.

compareTo(Object obj) method

Therefore to compare the current object with the specified object we used the syntax :

public int compareTo(Object obj)

Hence, Here is a list of what the element we can sort :

Continue reading What is a Comparable Interface?

Java SE 8 Lambda Expressions

Lambda expression is one of a lot of new and important feature of Java which specifically it’s Java SE 8. This feature (lambda Expressions) will provide one clear and concise way to represent interface method using an expression. The method is very useful in the collection library in so much way. Before the lambda expression, using an anonymous inner class was the only way and option for a coder to implement the method.

The new Java SE 8 feature Lambda expression provides coders an implementation of a functional interface. Functional Interface is an interface that has only one abstract method. Java provides an annotations @FunctionalInterface, which is used to declare an interface as a functional interface. 

Reason To Lambda Expressions:

  1. To do less coding.
  2. To have the implementation of Functional Interface 

Lambda Expression Syntax :

(argument-list) -> {body}  

Below I will tell you the components that built Lambda Expression:

  1. Body: Body Components contains statements  .etc for the lambda expression.
  2. Argument-list: An Argument-list you could fill it empty or filled as well.
  3. Arrow-token: The arrow token functionality is to link the arguments-list and body of statements.


Here is an Example without Lambda Expression in Interface:

    interface Colourable{ 
        public void colour(); 
    } 
    public class LambdaExpressionExample { 
        public static void main(String[] args) { 
            int width=7; 
     
            //without lambda we used anonymous inner class

            Colourable c=new Colourable(){ 
                public void draw(){System.out.println(“Drawing “+width);} 
            }; 
            c.colour(); 
        } 
    }  


Then compare it to the one that uses lambda Expression:

  @FunctionalInterface  //It’s optional 
    interface Colourable{ 
        public void colour(); 
    } 
     
    public class LambdaExpressionExample { 
        public static void main(String[] args) { 
            int width=7; 
             
            //with lambda  (less coding)
            Colourable c2=()->{ 
                System.out.println(“Drawing “+width); 
            }; 
            c2.colour(); 
        } 
    } 

  
 Conclusions :


Java Adapter Class

Java has a class named, Adapter class that provides an implementation of the listener interface. If your code inherit an adapter class, then you will not be forced to provide the implementation of all the methods. So adapter class saves code.
You can found adapter class in java.awt.event, java.awt.dnd and javax.swing. event packages. Here, look at a list of methods from Java Adapter class :

Java.awt.event :

  • WindowAdapter   : WindowListener
  • KeyAdapter   : KeyListener
  • MouseAdapter  :  MouseListener
  • MouseMotionAdapter :  MouseMotionListener
  • etc.

Javax.swing.event :

  • DragSourceAdapter  :  DragSourceListener
  • DragTargetAdapter   : DragTargetListener

 Java.awt.dnd :

  • MouseInputAdapter  :  MouseInputListener
  • InternalFrameAdapter  :  InternalFrameListener 

Here is an Exmpl of 1 method that Adapter class have :
 Window Adapter  :

//1st import
    import java.awt.*; 
    import java.awt.event.*; 
//2nd create methods and constructor
    public class AdapterExample{ 
        Frame f; 
        AdapterExample(){ 
            f=new Frame(“Window Adapter Exmpl”); 
            f.addWindowListener(new WindowAdapter(){ 
                public void windowClosing(WindowEvent e) { 
                    f.dispose(); 
                } 
            }); 
             
            f.setSize(300,300); 
            f.setLayout(null); 
            f.setVisible(true); 
        } 
//3rd call and run the methods
    public static void main(String[] args) { 
        new AdapterExample(); 
    } 
    } 

Conclusions

  • Adapter class saves code.
  • java.awt.event.
  • java.awt.dnd.
  • javax.swing.event

Program… listen to Mouse! (MouseListener)

Yes… You can listen to your mouse, I mean not literally but.. you can make your program act as when you do something with you mouse, for example : make your program print out something when you click your mouse. Java MouseListener acts whenever the state of the mouse is changed. The MouseListener is notified agains MouseEvent. You can found MouseListener interface in a java.awt.event package. It has five methods.

Check these methods out :

  • public abstract void mouseClicked(MouseEvent e);  //when you click the mouse
  • public abstract void mouseEntered(MouseEvent e);  //when you entered the mouse / move
  • public abstract void mouseExited(MouseEvent e);  //when you exited the mouse / don’t move
  • public abstract void mousePressed(MouseEvent e);  //when you press / drag the mouse 
  • public abstract void mouseReleased(MouseEvent e);  //when you release the mouse  


 Anyway, that’s that for the theory, now you know what time it is !
It’s Exmpl time! :

//1st import
   import java.awt.*; 
    import java.awt.event.*;
//2nd create the Method/object and constructor of MouseListener 
    public class MouseListenerExmpl extends Frame implements MouseListener{ 
        MouseListenerExmpl(){ 
            addMouseListener(this); 
             
            setSize(300,300); 
            setLayout(null); 
            setVisible(true); 
        } 
        public void mouseClicked(MouseEvent e) { 
            Graphics g=getGraphics(); 
            g.setColor(Color.GREEN); 
            g.fillOval(e.getX(),e.getY(),30,30); 
        } 
        public void mouseEntered(MouseEvent e) {} 
        public void mouseExited(MouseEvent e) {} 
        public void mousePressed(MouseEvent e) {} 
        public void mouseReleased(MouseEvent e) {}           
//3rd call and run the method and constructor
    public static void main(String[] args) { 
        new MouseListenerExmpl(); 
    } 

and it’ll output this :

Java Layout : BorderLayout

Layout… The Java Layout Managers, is always used to arrange components in some particular manner. LayoutManager is actually an interface that’s implemented by all layout managers classes. Here’s a list of classes that represents LayoutManagers :

  1. java.awt.BorderLayout.
  2. java.awt.FlowLayout.
  3. java.awt.GridLayout.
  4. java.awt.CardLayout.
  5. javax.swing.BoxLayout
  6. javax.swing.GroupLayout etc.


BorderLayout
BorderLayout Layout is used to arrange components into five regions : north, south, east, west and center. Each region can only contain only one components. The BorderLayout is default layout for Frame or window. And also don’t forget, BorderLayout provides five constants for each region:

  • public static final int NORTH
  • public static final int SOUTH
  • public static final int CENTER 
  • public static final int EAST
  • public static final int WEST

 There are 2 types of constructor that builds BorderLayout ;

  1. BorderLayout(); //creates a border without any gaps between the regions
  2. JBorderLayout(int hgap, int vgap); //creates a border with a gap for the horizontal and vertical lines between the regions.

It’s Exmpl Time ! :

    import java.awt.*; 
    import javax.swing.*; 
     
    public class Border { 
    JFrame f; 
    Border(){ 
        f=new JFrame(); 
         
        JButton b1=new JButton(“NORTH”);; 
        JButton b2=new JButton(“SOUTH”);; 
        JButton b3=new JButton(“EAST”);; 
        JButton b4=new JButton(“WEST”);; 
        JButton b5=new JButton(“CENTER”);; 
         
        f.add(b1,BorderLayout.NORTH); 
        f.add(b2,BorderLayout.SOUTH); 
        f.add(b3,BorderLayout.EAST); 
        f.add(b4,BorderLayout.WEST); 
        f.add(b5,BorderLayout.CENTER); 
         
        f.setSize(500,500); 
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    } 
    public static void main(String[] args) { 
        new Border(); 
    } 
    } 

This will output this :


Conclusions

  • The Java Layout Managers, is always used to arrange components in some particular manner.
  • LayoutManager is actually an interface that’s implemented by all layout managers classes.
  • BorderLayout Layout is used to arrange components into five regions : north, south, east, west and center. 

Queues in Java

Queues in Java is an interface that’s basically orders an element in FIFO or First In First OUT manner.

Here is the methods available Queue Interface :

  • public boolean add(object);
  • public boolean offer(object);
  • public remove();
  • public poll();
  • public element();
  • public peek();

After Queues interface it comes with the PriorityQueue, and PriorityQueue is a class that provides the facillity of using the queue interface, but one thing you need to remember is that PriorityQueue class doesn’t order an element in FIFO manners not like Queue Interface.


Example time ! :
 

    import java.util.*; 
    class PriorityQueueExmpl{ 
    public static void main(String args[]){ 
     
    PriorityQueue<String> queue=new PriorityQueue<String>(); 
    queue.add(“Umat”); 
    queue.add(“Linay”); 
    queue.add(“Breane”); 
    queue.add(“Ceasar”); 
    queue.add(“Rhealdy”); 
           
    System.out.println(“iterating the queue elements:”); 
    Iterator itr=queue.iterator(); 
    while(itr.hasNext()){ 
    System.out.println(itr.next()); 
    } 
     
    queue.remove(); 
    queue.poll(); 
     
    System.out.println(“after removing two elements:”); 
    Iterator<String> itr2=queue.iterator(); 
    while(itr2.hasNext()){ 
    System.out.println(itr2.next()); 
    } 
     
    } 
    }
 

This will output :

iterating the queue elements:

Umat
Breane
Ceasar
Linay
Rhealdy
after removing two elements
Ceasar
Rhealdy


Conclusions 

  • Queues in Java is an interface that’s basically orders an element in FIFO or First In First OUT manner.
  • PriorityQueue class doesn’t order an element in FIFO manners not like Queue Interface.

Java HashSet Class

HashSet class in java, is like a list but different. It has some differences with list, well to know that let me tell you about the details of HashSet class :

  • HashSet uses HashTable to store elements. It extends AbstractSet class and implements Set interface.
  • HashSet can only contain unique elements (no duplicate elements allowed).

After seeing the specification of HashSet we can tell its differences with list now, the one only noticeable differences is that, HashSet can only contain unique elements and since List can have duplicate elements, it makes the difference.


Here is a plain drawn hierarchy of somewhat the family-tree of the HashSet is :
It starts from the lowest to the highest :

HashSet –>(extends)AbstractSet –>(implements) set –>(extends) collection –>(extends) Iterable.

okay, guess that’s enough because HashSet is not a hard thing to learn, its just one of many java basics. And now, it’s example time! :

    import java.util.*; 
    class HashSetExmpl{ 
     public static void main(String args[]){ 
      
      HashSet<String> al=new HashSet<String>(); 
      al.add(“Raffi”); 
      al.add(“Jeay”); 
      al.add(“Raffi”); 
      al.add(“Vices”); 
     
      Iterator<String> itr=al.iterator(); 
      while(itr.hasNext()){ 
       System.out.println(itr.next()); 
      } 
     } 
    }  

This will output :

Raffi
Jeay
Vices

You might wonder “why there are only 1 Raffi, instead of 2 just like I add it to the HashSet. You see, from the beginning I already told you that HashSet can only contain unique elements, it means it could not have any duplicate elements, and because of that the string Raffi is only outputted once.

conclusions

  • HashSet uses HashTable to store elements. It extends AbstractSet class and implements Set interface.
  • HashSet can only contain unique elements (no duplicate elements allowed).
  • Hierarchy :
    • HashSet –>(extends)AbstractSet –>(implements) set –>(extends) collection –>(extends) Iterable.

Iterating List == ListIterator Interface

Ever heard of ListIterator? Ever try it on real life coding?, if no then let’s try it together.A few little thing that you need to know before we start, ListIterator interface contains a method that can insert or delete, and.. transverse element in forwards even backwards direction, oh and yea! I forgot to mention that ListIterator interface is a subinterface out of Collection keep that in mind.The method in the ListIterator interface only consist of 7 method, which I’m sure you’ll get the hang of it if you understand the whole thing and you get enough practice. Let’s start with knowing the method that List interface provide :

First:
public void add(int index, Object element);
This method is used to add an element/object into the collection.


Second:
public void add(int index, Collection c);
This method is used to add a collection of an element to an existing collection.

Third:
public object get(int index position);
This method is used to get (output) an element from a collection based on the index position.

Fourth:
public object set(int index, object element);
This method is used to set/replace an existing element from inside a collection.

Fifth :
public object remove(int index position);
Now for this one is different from the methods before, because this method remove an object from the collection instead of set/create/get an element from a collection.

Sixth and Seventh :
public ListIterator listIterator();
public ListIterator listIterator(int i);
This methods is the one that iterate and list the collection of object.

For the record, the method above is methods that is frequently used in List interface, we haven’t got into the ListIterator yet, the methods that is frequently used in ListIterator interface are 4 methods, see them :

  • public boolean hasNext(); This method will check if there are any object left in the collection in forward direction.
  • public object next(); This method will output the next object in the collection if hasNext() boolean turns out to be true.
  • public boolean hasPrevious(); This method will check if there are any object left in the collection in backwards direction.
  • public object previous(); This method will output the next object in the collection if hasPrevious() boolean turns out to be true.

Now let’s take an example, let’s work with  the method : add, set,and we’ll iterate the list in backwards direction just to make things a little bit more interesting. Now, let’s go ! :

    import java.util.*; 
    public class ListIteratorExmpl{ 

    public static void main(String args[]){ 
    ArrayList<String> li=new ArrayList<String>(); 

    //first we create an array (which is the collection of object/element)
    li.add(“Ipang”);  //we add the first element to array li which is “Ipang”
    li.add(“Ipeng”);  //we add the second element to array li which is “Ipeng”
     
    System.out.println(“Now the 1st element is : “+ li.set(1, “Ipung”)); 

   /*we set and overwrite the first element from “Ipang” to “Ipung”, now the first elemet is”Ipung”*/
     
    ListIterator<String> itr = li.listIterator();   //now we create the iterator    
     
    System.out.println(“Now we are iterating elements in a backward direction :”); 
    while(itr.hasPrevious()){  

    /*this will make a boolean condition to true based on : while there are still objects in the array in backwards direction*/
    System.out.println(itr.previous());

   /* this is a continuation from the boolean above, if true : output the objects over and over until there are no objects left in backwards direction other way false */ 
     } 
    } 
    }  

This program will output :
Now the 1st element is : Ipung
Ipeng
Ipung // which actually before this was Ipang, but we changed it in the set() method.

You see that it outputs the array in backwards direction? its because we’re using the previous() method.

 Conclusions 

  • ListIterator interface contains a method that can insert or delete, and.. transverse element in forwards even backwards direction.
  • ListIterator interface is a subinterface out of Collection
  • There are 7 frequently used method in List interface.
  • There are 4 frequently used method in ListIterator interface.
  • We can output values from forwards nor backwards direction.

Java Regex

Hello… How are you? I’m back again after 1 week of silence. And now we’re going to talk about java again, the subject for today is something related to java (of course) and Strings, and it is called Java Regex. Java Regex may sound odd to you, for the first time I heard java regex I thought it must’ve been something related to registration since the word is regex. But the actual meaning is not that close to registration, just like I said above it is actually related to strings and manipulation.

For the definition itself, Java Regex (Regular Expression) is an API that is created and mainly used to define a pattern for searching and manipulating strings.
Most of the time it is used to define constraint on a strings, i.e email validation or a password. I hope after knowing java regex, you’ll be able to do and make some regular expressions or regex using the Java Regex Tester Tool.

For the record, java regex API is provided with 1 interface and 3 classes in the java.util.regex package, which is the one that are in this list :

  • Interface :
    • MatchResult interface
  • Classes :
    •  Matcher class 
    •  Pattern class
    •  PatterSyntaxException

Both of the Matcher class and the Patter class have their own methods, which are provided in this list

Matcher class
the matcher class implements the MatchResult interface. And is used to match an operation of a character. 

  1. boolean matches()   // test whether the regular expression matches the pattern.
  2. boolean find()    //finds the next expression that matches the pattern.
  3. boolean find(int start)  //  finds the next expression that matches the pattern from the given startnumber.
  4. String group()  //  returns the matched subsequence.
  5. int start()   // returns the starting index of the matched subsequence.
  6. int end()  //  returns the ending index of the matched subsequence.
  7. int groupCount()  //  returns the total number of the matched subsequence

Patter class
the pattern class is the compiled version of the regular expression (regex), it is used to define a pattern for the regex machine.

  1. static Pattern compile(String regex)   // compiles the given regex and return the instance of pattern.
  2. Matcher matcher(CharSequence input)  //  creates a matcher that matches the given input with pattern.
  3. static boolean matches(String regex, CharSequence input) //   It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.
  4. String[] split(CharSequence input)  //  splits the given input string around matches of given pattern.
  5. String pattern() //   returns the regex pattern. 

It’s example time !!! :

     import java.util.regex.*; 
    public class RegexExmpl{ 
    public static void main(String args[]){ 
    //the 1st way 
    Pattern p = Pattern.compile(“.s”);//the dot (.) represents single character 
    Matcher m = p.matcher(“as”); 
    boolean b1 = m.matches(); 
     
    //2nd way 
    boolean b2=Pattern.compile(“.s”).matcher(“as”).matches(); 
     
    //3rd way 
    boolean b3 = Pattern.matches(“.s”, “as”); 
     
    System.out.println(b+” “+b2+” “+b3); 
    }}
 

This will output :

true true true

All off the methods above simply work by matchin one string to the second string and return it as a boolean (true or false).

Conclusions

  • Java Regex is related to strings manipulation.
  • Java Regex (Regular Expression) is an API that is created and mainly used to define a pattern for searching and manipulating strings.
  • Most of the time it is used to define constraint on a strings, i.e email validation or a password.
  • java.util.regex package contains : 1 interface and 3 classes.
  • boolean matches() Method implements MathResult().