当前位置: 技术问答>java相关
大家帮忙看看这段小程序
来源: 互联网 发布时间:2015-10-01
本文导语: import java.util.*; class Word { private int count = 1; private String word; Word(String w) { word = w; } int readCount() { return count; } String readWordString() { return word;...
import java.util.*;
class Word {
private int count = 1;
private String word;
Word(String w) {
word = w;
}
int readCount() {
return count;
}
String readWordString() {
return word;
}
void countIncrement() {
count++;
}
public boolean equals(Object o) {
return (
(o instanceof Word) &&
( word.equals( ((Word) o).readWordString() ) )
);
}
}
public class Test {
public static void main(String[] args) {
TreeSet words = new TreeSet();
Word a = new Word("aaaaa");
words.add(a);
System.out.println(words);
Word b = new Word("bbbbb");
if (!words.contains(b)) {
words.add(b);
}
System.out.println(words);
}
}
为何编译后运行时出现ClassCastException
class Word {
private int count = 1;
private String word;
Word(String w) {
word = w;
}
int readCount() {
return count;
}
String readWordString() {
return word;
}
void countIncrement() {
count++;
}
public boolean equals(Object o) {
return (
(o instanceof Word) &&
( word.equals( ((Word) o).readWordString() ) )
);
}
}
public class Test {
public static void main(String[] args) {
TreeSet words = new TreeSet();
Word a = new Word("aaaaa");
words.add(a);
System.out.println(words);
Word b = new Word("bbbbb");
if (!words.contains(b)) {
words.add(b);
}
System.out.println(words);
}
}
为何编译后运行时出现ClassCastException
|
刚才说错了
是必须实现
java.lang.Comparable
不是
java.util.Comparator
是必须实现
java.lang.Comparable
不是
java.util.Comparator