Given:
import java.util.*;
public class CompareTest {
public static void main(String[] args) {
TreeSet<String> set1 = new TreeSet<String>(
new Comparator<String>() {
public boolean compare(String s1, String s2) {
return s1.length() > s2.length();
}
});
set1.add(“peach”);
set1.add(“orange”);
set1.add(“apple”);
for (String n: set1) {
System.out.println(n);
}
}
}
What is the result?
A.
peach
orange
apple
B.
peach
orange
C.
apple
orange
D.
The program does not compile.
E.
The program generates an exception at runtime.
Explanation:
The compiler has a problem with the line:
public boolean compare(String s1, String s2) {
return s1.length() > s2.length();error: <anonymous comparetest.CompareTest$1> is not abstract and does not override abstract method compare(String,String) in Comparator
new Comparator<String>() {Error: compare(String,String) in <anonymous comparetest.CompareTest$1> cannot implement compare(T,T) in Comparator
public boolean compare(String s1, String s2) {
return type boolean is not compatible with int
where T is a type-variable:
T extends Object declared in interface Comparator
if fixing compile defects, the result should be B
Agreed if the complilation error is fixed. Set does not allow duplicated items. ‘peach’ and ‘apple’ has same length so are regarded as duplicates and only ‘peach’ is added.
C
Did anybody try to compile that? Comparator’s method compare must have an int return type.
Should be D. Because compare() should return int.
D. However, if the compare is fixed to the following, answer would be B.
public int compare(String s1, String s2) {
return s1.length() – s2.length();
}
The return type is incompatible with Comparator.compare(String, String)
1 fix available :
Change return type to int …
D
line:
public boolean compare(String s1, String s2) { return s1.length() > s2.length(); }
Compiler:
implements java.util.Comparator.compare
The return type is incompatible with Comparator.compare(String, String)