Both are interfaces in Java. Here some common differences between Comparator and Comparable.
- Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
- Comparator has the method int compare(T o1,T o2) which 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. While Comparable has method public int compareTo(T o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
- compare method of Comparator compares its two arguments for order. compareTo method of Comparable interface compares this object with the specified object for order.
- Comparator has equals(Object obj) method while Comparable doesn't.
0 comments:
Post a Comment