What is Comparable and Comparator interface? List their differences.
What is Comparable and Comparator interface? List their differences.
The Comparable and Comparator interfaces in Java are used for sorting collections of objects. Both interfaces are part of the Java Collections Framework but serve slightly different purposes.
The Comparable interface is used to define the natural ordering of objects. When a class implements the Comparable interface, it must provide an implementation for the compareTo()
method. This method compares the current object with the specified object and returns an integer value. The returned value is negative if the current object is less than the specified object, zero if they are equal, and positive if the current object is greater than the specified object.
Classes that implement Comparable can be sorted automatically by methods like Collections.sort()
and Arrays.sort()
without the need for a separate Comparator. The Comparable interface is found in the java.lang
package and contains only one method, compareTo(Object obj)
.
The Comparator interface is used to define a custom order for objects, which may be different from the natural order. When a class implements the Comparator interface, it must provide an implementation for the compare()
method. This method takes two arguments and compares them, returning a negative integer, zero, or a positive integer to indicate whether the first argument is less than, equal to, or greater than the second.
The Comparator interface is found in the java.util
package and contains two methods: compare(Object obj1, Object obj2)
and equals(Object element)
. It allows for multiple sorting sequences, meaning you can sort objects based on different attributes, such as name, age, or any other property.
Nature of Sorting Order:
Method of Sorting:
compareTo()
method to sort objects.compare()
method and can also use equals()
[5][7].Package:
java.lang
package.java.util
package[1][10].Implementation:
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào