cannot be cast to java.lang.Comparable

wangyy發表於2018-01-17

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,如果年齡相同,名字不同,仍然會當作一個人看待

所以需要用次條件進行判斷。

 

相關文章