Set集合中的treeSet问题:cannot be cast to java.lang.Comparable;
程序员文章站
2022-10-04 20:11:14
使用TreeSet保存自定义对象时, 必须让定义对象的类实现Comparable接口,并重写compareTo()方法 否则报 实体类User:cannot be cast to java.lang.Comparable异常 测试类Test ......
使用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()); } } }