我有一个扩展 HashSet 参数化版本的类。这个类有一个内部字段 currentSize
它跟踪到目前为止添加了多少元素。子类覆盖基类'add
和 addAll
方法所以 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/