【问题标题】:Is there a way for HashSet to return the duplicate of an object?HashSet 有没有办法返回对象的副本?
【发布时间】:2021-08-31 17:01:40
【问题描述】:

例如:

class SomeClass
{
    int x;
    int y;
    public SomeClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public boolean equals(Object o)
    {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        SomeClass that = (SomeClass) o;
        return x == that.x;
    }

    public int hashCode()
    {
        return Objects.hash(x);
    }
}

然后:

HashSet<SomeClass> hs = new HashSet<>();
SomeClass a = new SomeClass(3, 5);
SomeClass b = new SomeClass(3, 6);
hs.add(a);
hs.add(b);

我知道 HashSet 不会添加 b。但我希望它以某种方式返回对象a,因为ab 并不完全相同。

HashSet 会将它们视为相等并且不会添加b,在插入失败后我想检查对象a

tldr:

我需要一个可以做类似hs.getDuplicateOf(b) 的方法,这可能吗?

【问题讨论】:

  • 不清楚。 add() 返回 boolean
  • if (hs.contains(b)) { SomeClass copy = hs.stream().filter(o -&gt; o.equals(b)).findFirst().get(); }

标签: java collections hashset


【解决方案1】:

使用HashMap 应该适合您的需求:

Map<SomeClass, SomeClass> map = new HashMap<>();
SomeClass a = new SomeClass(3, 5);
SomeClass b = new SomeClass(3, 6);
SomeClass previousValue = map.put(a, a);
// previousValue == null
previousValue = map.put(b, b);
// previousValue == a

这将保留b 并删除a(从地图的值中),如果您需要相反的行为,请使用putIfAbsent 而不是put

相当老套,但你的 equals/hashCode 方法也是如此;)

【讨论】:

  • 嗯,很容易将其扩展到一个非 hacky 解决方案,只需使用 x 的值作为键。
【解决方案2】:

HashSet#add 如果此集合已包含指定元素,则返回。所以,你可以试试:

if(!hs.add(b)) {
    System.out.println("b already exists");
}

【讨论】:

  • 我特别想检查对象“a”的“y”值是什么,equals() 方法不依赖该值。我想说这样的话: if(!hs.add(b)) { System.out.println("duplicate's y value is: " + hs.getDuplicateOf(b).y ); }
猜你喜欢
  • 2016-03-07
  • 1970-01-01
  • 2013-08-08
  • 2021-03-11
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 2011-04-12
相关资源
最近更新 更多