• Set集合中的treeSet问题:cannot be cast to java.lang.Comparable;


     使用TreeSet保存自定义对象时,

    必须让定义对象的类实现Comparable接口,并重写compareTo()方法

    否则报

    实体类User:cannot be cast to java.lang.Comparable异常

    public class User implements Comparable<User>{
        private int age;
        private String name;
        private String pro;
        public User(String name,int age,String pro) {
            this.name = name;
            this.pro = pro;
            this.age = age;
        }
        
        @Override
        public int compareTo(User u) {
            if(this.age>u.age) {
                return 1;
            }else if(this.age==u.age) {
                return this.name.compareTo(u.name);
            }else {
                return -1;
            }
            
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPro() {
            return pro;
        }
    
        public void setPro(String pro) {
            this.pro = pro;
        }
    }

    测试类Test

    public class test{
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Set<User> set = new    TreeSet<User>();
            User user = new User("Java", 21,"小仙女");
            User user2 = new User("Spring",22,"小跟班");
            set.add(user);
            set.add(user2);
            System.out.println(set.size());
            //遍历方式一
    //        Iterator<User> it = set.iterator();
    //        while(it.hasNext()) {
    //            User u = it.next(); 
    //            System.out.println(u.getName());
    //        }
            for (User u : set) {
                System.out.println(u.getName()+","+u.getAge()+","+u.getPro());
            }
        }
    }
  • 相关阅读:
    Java -- JDBC 批处理
    Java -- JDBC mysql读写大数据,文本 和 二进制文件
    Python之操作符优先级
    闲聊之Python的数据类型
    UPX和WinUpack压缩壳的使用和脱法
    改进我们的小游戏
    Python while循环语法
    Python条件分支语法
    python条件分支
    小插曲之变量和字符串
  • 原文地址:https://www.cnblogs.com/Dandwj/p/9319848.html
Copyright © 2020-2023  润新知