前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >cannot be cast to java.lang.Comparable

cannot be cast to java.lang.Comparable

作者头像
yuanyuan
发布2019-09-10 18:03:05
2.6K0
发布2019-09-10 18:03:05
举报
文章被收录于专栏:小满小满

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;
      }
  }

运行结果:

cbh...10 wyy...20 cl...30

在该对象的compareTo方法中,判断年龄相等的条件时,若直接返回0,如果年龄相同,名字不同,仍然会当作一个人看待

所以需要用次条件进行判断。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档