the following is taken from joshua bloch's effective java. pg 82:
public class InstrumentedHashSet<E> extends HashSet<E> {
// The number of attempted element insertions
private int addCount = 0;
public InstrumentedHashSet() {
}
public InstrumentedHashSet(int initCap, float loadFactor) {
super(initCap, loadFactor);
}
@Override public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
my question is that how come super.addAll()
invokes the overridden add()
method instead of the add() method of the supeclass? the book says that doing this :
InstrumentedHashSet<String> s = new InstrumentedHashSet<String>();
s.addAll(Arrays.asList("Snap", "Crackle", "Pop"));
would give count result as 6 instead of 3 , as the count is first incremented in the overridden addAll() method , then super.addAll()
invokes the overridden add()
method where the counts are incremented again. i dont understand why the overridden add() gets invoked like this. also , i read the docs about addAll() , the only info it has about the linked add() method is this
Note that this implementation will throw an UnsupportedOperationException unless add is overridden (assuming the specified collection is non-empty).
this also , i felt was a little tight on info... asleast to less expirienced programmers...