上题:
QUESTION 5
Given:
1. public class Score implements Comparable<Score> {
2. private int wins, losses;
3. public Score(int w, int l) { wins = w; losses = l; }
4. public int getWins() { return wins; }
5. public int getLosses() { return losses; }
6. public String toString() {
7. return "<" + wins + "," + losses + ">";
8. }
9. // insert code here
10. }
Which method will complete this class?
A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}
Answer: B
Section: (none)
这个题看过好多次,一直没怎么明白它在考查什么,还和Comparator类混在一块了。
Comparable 和 Comparator 两个都是接口。唉,不说他了,这次只单说Comparable,因为我一看它里边的方法有好多,我就头疼。
相比之下,Comparable接口中的方法就比较乖了,就一个,嘿嘿。
代码是这样的:
public interface Comparable<T> {
public int compareTo(T o);
}
这下没什么好说的了,把题目拿来,对号入座,
C D不用考虑了,Comparable中就没这个方法(其实compara方法是Comparator中的方法);
A B呢,泛型嘛,题目类上怎么写的:public class Score implements Comparable<Score> ,很明显是 <Score>,选B。