Câu hỏi phỏng vấn Java
Câu hỏi

What is Comparable and Comparator interface? List their differences.

Câu trả lời

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.

Comparable Interface

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).

Comparator Interface

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.

Key Differences

  1. Nature of Sorting Order:

    • Comparable provides a single sorting sequence, which is the natural ordering of the class.
    • Comparator allows for multiple sorting sequences, enabling sorting based on different attributes[1][3][5].
  2. Method of Sorting:

    • Comparable uses the compareTo() method to sort objects.
    • Comparator uses the compare() method and can also use equals()[5][7].
  3. Package:

    • Comparable is part of the java.lang package.
    • Comparator is part of the java.util package[1][10].
  4. Implementation:

    • Comparable is implemented by the class of the objects that need to be compared.
    • Comparator is implemented in a separate class, allo...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What are the restrictions imposed on Java applets?

middle

Explain the life cycle of an Applet.

junior

Explain the architechure of a Servlet

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào