集合去重对象问题

tech2022-08-07  153

业务解决

public class Test { public static void main(String [] args){ User user = new User("1","2"); User user1 = new User("1","2"); User user2= new User("1","2"); List<User> list = new ArrayList<User>(); List<User> list1 = new ArrayList<User>(); list.add(user); list.add(user); list.add(user1); list.add(user2); list1.add(user); list1.add(user); list1.add(user1); list1.add(user2); list.addAll(list); List<User> listNew2 = new ArrayList<User>(new TreeSet<>(list)); System.out.println("listNew2 = " + listNew2); } }

实体类对象

public class User implements Comparable { private String name; private String addr; public User(String name, String addr) { this.name = name; this.addr = addr; } // 重写比较器 去重时TreeSet调用 @Override public int compareTo(Object o) { if (this.name.equals(((User) o).name)) { System.out.println("相等"); return 0; } return 1; } }
最新回复(0)