直接上代码,用的比较多
方式用用Set特性去重,但关键在于对象的equals()和hashCode()两个方法的重写
之所以在重写equals()的情况下,还需要重写hashCode()方法,是因为HashSet/HashMap/Hashtable 类存储数据时,都会根据存储对象的 hashCode 值来进行判断是否相同的
public static void main(String[] args) {
List<BoardVo> boardTyprCount=new ArrayList<>();
boardTyprCount.add(new BoardVo(0,8));
boardTyprCount.add(new BoardVo(0,8));
boardTyprCount.add(new BoardVo(1,16));
boardTyprCount.add(new BoardVo(1,16));
System.out.println("--------没有去重的----------");
for (BoardVo b: boardTyprCount ) {
System.out.println(b.toString());
}
System.out.println();
System.out.println("-----------去重后的--------------");
Set<BoardVo> set=new HashSet<>();
set.addAll(boardTyprCount);
for (BoardVo b:set) {
System.out.println(b.toString());
}
}
结果:
BoardVo类
public class BoardVo {
private Integer index;
private Integer type;
public BoardVo() {
}
public BoardVo(Integer index, Integer type) {
this.index = index;
this.type = type;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
return "BoardVo{" +
"index=" + index +
", type=" + type +
'}';
}
//关键在于这两个方法的重写------------重点!!!!!
@Override
public boolean equals(Object obj) {
BoardVo boardVo=(BoardVo)obj;
//这里因为参数定义的是Integer包装类,所以比较不能用==,要用equals(),否则当参数不在(-127,,128)之间的话它自动拆箱后是会报错的
//另外你要多少个参数可以决定这里就写多少个参数相等条件,同时下面的额hashCode()方法也要保持参数一致
return index.equals(boardVo.index) && type.equals(boardVo.type);
}
@Override
public int hashCode() {
String str=String.valueOf(index)+String.valueOf(type);
return str.hashCode();
}
}