I am trying to understand the source code:
public class InstrumentedSet extends HashSet {
// Keeps the number of attempted element insertions
private int addCount;
public InstrumentedHashSet(Collection c) {
super(c);
}
public boolean add(Object o) {
addCount++;
return super.add(o);
}
public boolean addAll(Collection c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
public static void main(String[] args) {
InstrumentedHashSet s = new InstrumentedHashSet();
String s1[] = new String[] {"Snap","Crackle","Pop"};
s.addAll(Arrays.asList(s1));
System.out.println(s.getAddCount());
}
}
}
I can not understand why does the main function return the execution value of 6 instead of the return value of 3.
Well, besides the fact that you current code doesn't compile it is possible to explain that behavior.
You're calling
addAllon your newInstrumentedHashSet(orInstrumentedSet) instance and this method looks like this:First you're adding 3 to
addCountand since that variable was 0 before, it will then be 3, as well.Then you're calling
addAllof thesuperclassHashSetand the implementation of it looks like this:The most important part is the
ifstatement:if (add(e)). It callsaddfor each item in the passedCollectionand since you've overriden that method with your own implementation:... that method will be called instead of the parent implementation. And here you're increasing
addCountfor each added element. So you're now counting each element a second time.And that is basically the reason why
System.out.println(s.getAddCount());prints the doubled amount of the passedCollectionfromArrays.asList(s1).