gpt4 book ai didi

java - HashSet addAll 方法修改类内部字段

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:04:42 26 4
gpt4 key购买 nike

我有一个扩展 HashSet 参数化版本的类。这个类有一个内部字段 currentSize它跟踪到目前为止添加了多少元素。子类覆盖基类'addaddAll方法所以 currentSize相应增加。我的问题是里面 addAll ,集合的大小被添加到 currentSize 的两倍柜台,不是一次。以下是我类(class)的代码:

public class InheritHashSet extends HashSet<Integer> {
private int currentSize = 0;

@Override
public boolean add(Integer e) {
currentSize++;
super.add(e);
}

@Override
public boolean addAll(Collection<? extends Integer> e) {
currentSize += e.size();
super.addAll(e);
}

public int getCurrentSize() {
return currentSize;
}
}

add方法似乎工作正常,因为在添加三个元素后,currentSize是 3,但以下将向 currentSize 添加 6而不是 3:

InheritHashSet ihs = new InheritHashSet();
Collection<Integer> c = new LinkedList<Integer>();
c.add(new Integer(0));
c.add(new Integer(1));
c.add(new Integer(2));
ihs.addAll(c);
System.out.println(ihs.getCurrentSize()); // prints 6 instead of 3

看起来像是对 super.addAll(e) 的调用还修改了 currentSize (这似乎根本没有任何意义)。

最佳答案

InheritHashSet类的addAll()方法首先设置currentSize = 3,用currentSize += e.size();指令.然后 super.addAll(e); 调用了三次 add(e) 方法。对于动态绑定(bind),首先调用 InheritHashSet 类的 public boolean add(Integer e),然后将 currentSize 递增到 6。

因此,您应该以这种方式实现 addAll 方法:

@Override
public boolean addAll(Collection<? extends Integer> e) {
return super.addAll(e);
}

关于java - HashSet addAll 方法修改类内部字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com