COMPARABLE AND COMPARATOR


Comparable - This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or elements in a sorted set, without the need to specify a comparator.
package java.lang;
public interface Comparable<T> {

        /**
         * Compares this object with the specified object for order.  Returns a
         * negative integer, zero, or a positive integer as this object is less
         * than, equal to, or greater than the specified object.
         */
        public int compareTo(T o);
}

                                                               
Comparator - Represents an order relation, which may be used to sort a list or maintain order in a sorted set or map. Can override a type's natural ordering, or order objects of a type that does not implement the Comparable interface.
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).
package java.util;

public interface Comparator<T> {
        /**
         * Compares its two arguments for order.  Returns a negative integer,
         * zero, or a positive integer as the first argument is less than, equal
         * to, or greater than the second.
         */
        int compare(T o1, T o2);
       
        boolean equals(Object obj);
}

People who read this post also read :



2 comments:

Amazing Article, thank you!. I am very glad to read your informative & practical blog. Kindly keep updating your blog.
Java Developer is a wonderful career for IT students.To start Dream Career to become a Java developer learn from
Java Training in Chennai
. or learn thru Java Online Training from India .

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More