Which code fragment represents a valid Comparator implementation?
Which code fragment represents a valid Comparator implementation?
To implement a valid Comparator in Java, you must override the compare method from the Comparator interface, which should take two arguments and return an int. Option C correctly implements the compare method, taking two strings and using the compareTo method to return a comparison result. This makes Option C a valid implementation of a Comparator. Option A incorrectly tries to use the compareTo method directly within the Comparator and Option D has an incorrect return type and method signature for a Comparator.
Correct answer is C . //A is invalid because :The type new Comparator<String>(){} must implement the inherited abstract method Comparator<String>.compare(String, String) //B is invalid because : The type Comps must implement the inherited abstract method Comparator.compare(Object, Object) //D is invalid because : The return type is incompatible with Comparator.compare(Object, Object) and Illegal modifier for the local class Comps; only abstract or final is permitted
Tested
c is correct
Comparator use compare and String implement Comparable who use compareTo so C is correct
c , Comparator has method compare no compareTo, can used in method compare
C is correct