Web / Apache Commons Collections Interview questions
Why doesn't a Bag simply behave like a Set?
A Set's contract is built entirely around uniqueness: calling add() with a value that's already present is a no-op that returns false, and the set's size only ever reflects distinct elements. That contract structurally cannot represent "how many times did this occur" - the information is thrown away by design.
Set<String> set = new HashSet<>(); set.add("error"); set.add("error"); System.out.println(set.size()); // 1 - the second add did nothing Bag<String> bag = new HashBag<>(); bag.add("error"); bag.add("error"); System.out.println(bag.getCount("error")); // 2 - both adds were recorded
A Bag is closer to the mathematical concept of a multiset: it intentionally keeps duplicates and exposes getCount(Object) to answer "how many," which is exactly the information a Set discards on the second identical add() call.
This makes Bag the natural structure for tallying tasks - word-frequency counting, vote tallying, inventory counts by SKU - where a Set would force you to bolt on a separate counter map just to recover the information a Bag tracks natively.
More Related questions...