【问题标题】:override equals in a java set [duplicate]覆盖java集中的等于[重复]
【发布时间】:2021-12-31 03:08:42
【问题描述】:

如何防止集合中包含重复的数组?

    Set<int[]> set = new HashSet<>();
    int[] tmp = new int[]{1,2};
    set.add(tmp);
    tmp = new int[]{1,2};
    set.add(tmp);
    System.out.println(set.size());

我希望集合只包含一个元素。

【问题讨论】:

  • 使用ArrayList&lt;Integer&gt; 而不是int[]。或者实现您自己的包含 int 数组的包装类,然后您可以覆盖 hashCodeequals
  • 我认为这里可能存在更深层次的体系结构问题,为什么要将 int 数组(而不是自定义数据类型)添加到 Set
  • 你可以wrap each array in an IntBuffer,因为 IntBuffer 提供了有意义的 equals 和 hashCode 方法。 (只是不要在创建缓冲区后更改任何缓冲区的位置或限制。)

标签: java equals hashset


【解决方案1】:

您可以使用TreeSet

TreeSet 使用Comparable.compareTo()Comparator.compare() 代替hashCode()equals() 来比较元素。可以在构造函数中指定。

public static void main(String[] args) {
    Set<int[]> set = new TreeSet<>(Arrays::compare);
    set.add(new int[]{1,2});
    set.add(new int[]{1,2});
    System.out.println(set.size());
}

输出:

1

Arrays::compare 是一个Comparator,它按字典顺序比较数组。

【讨论】:

    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2012-11-05
    • 2013-02-08
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2015-03-17
    相关资源
    最近更新 更多