cannot be cast to java.lang.Comparable
Exception in thread "main" java.lang.ClassCastException: com.myradio.People cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at com.myradio.TreeSetDemo.methodTreeSet(TreeSetDemo.java:18)
at com.myradio.TreeSetDemo.main(TreeSetDemo.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
出现这个问题的原因:
TreeSet中的元素必须是Comparable类型。 字符串和包装类在默认情况下是可比较的。 要在TreeSet中添加用户定义的对象,该对象需要实现Comparable接口。
TreeSet的应用例子
import android.support.annotation.NonNull;import java.util.Iterator;
import java.util.TreeSet;
/**
* 1. order by people age
* 2. If both People object have the name and age as the same person
*/
public class TreeSetDemo {
public static void main(String [] args){
methodTreeSet();
}
private static void methodTreeSet(){
TreeSet ts = new TreeSet();
ts.add(new People("wyy",20));
ts.add(new People("cl",30));
ts.add(new People("cl",30));
ts.add(new People("cbh",10));
Iterator it = ts.iterator();
while (it.hasNext()){
People p = (People) it.next();
System.out.println(p.getName() + "..." + p.getAge());
}
}
}
class People implements Comparable{
String name;
int age;
People(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
@Override
public int compareTo(@NonNull Object o) {
if(!(o instanceof People)){
throw new RuntimeException("Not People object");
}
People p = (People) o;
if(this.age > p.getAge())
return 1;
if(this.age == p.getAge()) //if just this one condition, when the age is the same ,it will be treated as one people
return this.name.compareTo(p.getName()); //So compare name are needed.
return -1;
}
}
View Code
运行结果:
cbh...10
wyy...20
cl...30
在该对象的compareTo方法中,判断年龄相等的条件时,若直接返回0,如果年龄相同,名字不同,仍然会当作一个人看待
所以需要用次条件进行判断。
以上是 cannot be cast to java.lang.Comparable 的全部内容, 来源链接: utcz.com/z/393304.html