问题遇到的现象和发生背景
不想重写对象的equals和hashcode方法,想直接通过new TreeSet(Comparator)进行对象去重,但发现去重不彻底
问题相关代码,请勿粘贴截图
public class Comment {
private String dimensionKey;
private String dimensionValue;
private String indicatorsKey;
private String indicatorsValue;
}
List<Comment> comments = new ArrayList<>();
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("30").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("3").indicatorsKey("1").indicatorsValue("60").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("10").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("2").indicatorsKey("1").indicatorsValue("40").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("2").indicatorsKey("1").indicatorsValue("50").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("20").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("3").indicatorsKey("1").indicatorsValue("70").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("30").build());
TreeSet<Comment> set = new TreeSet<>((a, b) -> {
if (Objects.equals(a.getDimensionKey(), b.getDimensionKey()) &&
Objects.equals(a.getDimensionValue(), b.getDimensionValue()) &&
Objects.equals(a.getIndicatorsKey(), b.getIndicatorsKey())) {
return 0;
}
return 1;
});
set.addAll(comments);
运行结果及报错内容
很明显,是想利用dimensionKey+dimensionValue+indicatorsKey这三个属性的组合去重,根据我造的数据,最终结果只有3个才对,但实际上出现了四个。
下面是运行结果,可以看到2020.1.1没有去重彻底