Comparable
- It present in Java.lang Package.
- It Contains only one Method.
- Comparable can be used for natural or default sorting ordering.
Method
- public int compareTo(Object obj1,obj2)
- Return(-ve), iff obj1 has to come before obj2.
- Return(+ve), iff obj1 has to come after obj2.
- Return(0), iff obj1 & obj2 are equal.
foreg:
- System.out.println("A".compareTo("z"));
- System.out.println("z".compareTo("k"));
Return value is positivetive/(+ve)
- System.out.println("A".compareTo("A"));
Return value is Zero/(0)
- System.out.println("A".compareTo("null"));
Object1:-The Object, which is to be Inserted.
Object2:-The Object, which is already Inserted.
If We are Depending on Default Natural Sorting Order while adding object in to the TreeSet JVM will call (compareTo) method.
Note:
- If Default Natural Sorting Order not available or if we are not satisfied with Default Natural Sorting Order, than we can go for Customizer Sorting by using Comparator.
Comparator
- It present in java.util.Package.
- Comparator can be used for custom ordering.
- It defines Two Methods.
- compare()
- equals()
Method
- public int compare(object obj1, obj2)
obj1.compareTo(obj2)
- Return(-ve), iff obj1 has to come before obj2.
- Return(+ve), iff obj1 has to come after obj2.
- Return(0), iff obj1 & obj2 are equal.
2.public boolean equals(obj)
- Whenever we are implementing Comparator interface compulsory we should provide implementation only for compare method.
- we are not required to provide implementation for equals method .Because it is already available to our class from object class through Inheritance.
For eg of Comparator
- Write a program To Insert Objects into the TreeSet, Where the Sorting order is Descending Order
Output is
- If we are not Passing comparator Object than internally JVM will call comparatorTo method, which is meant for Default Natural Sorting Order, In this case the output is
- [0,5,10,15,20]
- If we are passing compare object than, JVM will call compare method which meant for Customizer Sorting in this case output is
- [20,15,10.5,0]
Various implementation of compare method
for eg: Main class