Comparator Interface in java
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new
techniques news and any history.
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new
techniques news and any history.
Comparator Interface
In Java, Comparator interface is used to order the object in your own way. It gives you the ability to decide how elements are stored within a sorted collection and map.
Comparator Interface defines the method
compare(). This method compares two objects and returns 0 if two objects are equal. It returns a positive value if object1 is greater than object2. Otherwise, a negative value is return. The method can throw a ClassCastException if the type of object is not compatible for comparison.Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object will be stored in ascending order of their roll.
class MyComparator implements Comparator{ public int compare(Student s1,Student s2) { if(s1.roll == s2.roll) return 0; else if(s1.roll > s2.roll) return 1; else return -1; } }
public class Test
{
public static void main(String[] args)
{
TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());
ts.add(new Student(45, "Rahul"));
ts.add(new Student(11, "Adam"));
ts.add(new Student(19, "Alex"));
System.out.println(ts);
}
}
Output :
[ 11 Adam, 19 Alex, 45 Rahul ]
As you can see in the output Student object are stored in ascending order of their roll.
Legacy Classes
The early version of Java did not include the Collection framework. It only defined several classes and interface that provide a method for storing objects. When Collection framework was added in J2SE 1.2, the original classes were re-engineered to support the collection interface. These classes are also known as Legacy classes. All legacy classes and interface were redesigns by JDK 5 to support Generics.
The following are the legacy classes defined by java.util package
- Dictionary
- HashTable
- Properties
- Stack
- Vector
There is only one legacy interface called Enumeration
NOTE: All the legacy classes are a syncronized
Enumeration interface
- Enumeration interface defines a method to enumerate through a collection of object.
- This interface is suspended by Iterator interface.
- However, some legacy classes such as Vector and Properties defines several methods in which Enumeration interface is used.
- It specifies the following two methods
boolean hasMoreElements() Object nextElement()
Vector class
- Vector is similar to ArrayList which represents a dynamic array.
- The only difference between Vector and ArrayList is that Vector is synchronized while Array is not.
- Vector class has following four constructor
Vector() Vector(int size) Vector(int size, int incr) Vector(Collection< ? extends E> c)
Vector defines several legacy methods. Let's see some important legacy method define by Vector class.
| Method | Description |
|---|---|
| addElement() | add element to the Vector |
| elementAt() | return the element at specified index |
| elements | return an enumeration of element in vector |
| firstElement() | return first element in the Vector |
| lastElement() | return last element in the Vector |
| removeAllElement() | remove all element of the Vector |
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en = ve.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
}
}
Output :
10 20 30 40 50 60
Hashtable class
- Like HashMap, Hashtable also stores key/value pair in hashtable. However neither keys nor values can be null.
- There is one more difference between HashMap and Hashtable that is Hashtable is synchronized while HashMap is not.
- Hashtable has following four constructor
Hashtable() Hashtable(int size) Hashtable(int size, float fillratio) Hashtable(Map< ? extends K, ? extends V> m)
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
}
}
Output:
a 100 b 200 c 300 d 400
Difference between HashMap and Hashtable
| Hashtable | HashMap |
|---|---|
| Hashtable class is synchronized. | hashmap is not synchronized. |
| Because of Thread-safe, Hashtable is slower than HashMap | HashMap works faster. |
| Neither key nor values can be null | Both key and values can be null |
| Order of table remains constant over time. | does not guarantee that order of map remains constant over time. |
Properties class
- Properties class extends Hashtable class.
- It is used to maintain a list of value in which both key and value are String
- Properties class define two constructor
Properties() Properties(Properties default)
- One advantage of Properties over Hashtable is that we can specify a default property that will be useful when no value is associated with a certain key.
Example of Properties class
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Properties pr = new Properties();
pr.put("Java", "James Ghosling");
pr.put("C++", "Bjarne Stroustrup");
pr.put("C", "Dennis Ritchie");
pr.put("C#", "Microsoft Inc.");
Set< ?> creator = pr.keySet();
for(Object ob: creator)
{
System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );
}
}
}
Output :
Java was created by James Ghosling C++ was created by Bjarne Stroustrup C was created by Dennis Ritchie C# was created by Microsoft Inc


Comments
Post a Comment