Set集合是针对String和8大基础数据类型过滤掉重复数据,如果存放的是其他类型对象,则需要重写hashCode方法和equals方法,当equals比较相等时,则会去比较hashCode的值 如果一致的话,则不会存进set容器.
去重方法:
在实体类中,重写重写hashCode方法和equals方法
public class 类名 implements Serializable { private String id; private String name; // set对象重复禁止添加,重写顶级方法 @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(this == obj) { return true; } if(obj instanceof 类名){ 类名 xx =(类名)obj; // 对象比较一个字段时 //if(xx.id.equals(this.id)){ // return true; //} 对象比较多个字段时, 用&& 隔开 if(xx.id.equals(this.id) && xx.name.equals(this.name)){ return true; } } return false; } @Override public int hashCode() { // 一个参数时 // return id.hashCode(); // 多个参数时 return id.hashCode() * name.hashCode(); } set,get方法... }