public class Person{
private static long counter = 0;
private final long id = counter++;
public long getId(){
return id;
}
public String toString(){
return super.toString()+" "+id;
}
public boolean equals(Object obj){
if(obj instanceof Person){
Person p = (Person)obj;
if(this.getId() == p.getId()){
return true;
}
}
return super.equals(obj);
}
public int hashCode(){
return String.valueOf(id).hashCode();
}
}
为什么会报如下错误:
Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at PersonWithCollection.main(PersonWithCollection.java:21) 作者: 温少邦 时间: 2012-7-11 16:27
TreeSet是一个有序的集合
所以创造一个Person类的TreeSet必须自己指定怎么去比较Person对象:
在构造TreeSet时传递一个Comparator对象
或者让Person类实现Comparable接口,覆盖compareTo方法作者: 全海波 时间: 2012-7-11 16:37
public class Person{
private static long counter = 0;
private long id = counter++;//这里错了,不能用final修饰
public long getId(){
return id;
}
public String toString(){
return super.toString()+" "+id;
}
public boolean equals(Object obj){
if(obj instanceof Person){
Person p = (Person)obj;//这里错了,这个叫做类型转换异常,不能将人转换成人
if(this.getId() == p.getId()){
return true;
}
}
return super.equals(obj);
}
public int hashCode(){
return String.valueOf(id).hashCode();
}
}