Java OCA OCP Practice Question 2408

Question

Which code option when inserted at //INSERT CODE HERE will enable you to sort instances of class Student using their natural order and add them to a TreeSet?.

class Student implements Comparator<Student> {
    String id;
    String name;
    //INSERT CODE HERE
}
a  public boolean compare(Object obj1, Object obj2) {/* relevant code here */}
b  public int compare(Object obj1, Object obj2) {/* relevant code here */}
c  public boolean compareTo(Student s1, Student s2) {/* relevant code here */}
d  public boolean compare (Object obj1) {/* relevant code here */}
e  public int compare(Student obj1) {/* relevant code here */}
f  None of the above


f

Note

Instances of a class are sorted using its natural order, if the class implements the Comparable interface and not Comparator.

The Comparator interface is used to define how to compare two objects for sorting (less than, equal to, or greater than).

Unlike the Comparable interface, the Comparator interface need not be implemented by the class whose objects are to be sorted.

The Comparator interface can be used to define an order for objects if the objects don't define their natural order.

It can also be used to define a custom order for objects.

You can use a Comparator object to define an order for objects, the natural order of which you can't define or modify.

When you pass a Comparator object to the instantiation of a collection class like TreeMap, the TreeMap uses the order as defined by the Comparator object, ignoring the natural order of its keys.

For example, the following class defines a custom (descending) order for String objects:

class DescendingStrings implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s2.name.compareTo(s1.name);
    }
}



PreviousNext

Related