Web / Apache Commons Collections Interview questions
What is a Bag in Apache Commons Collections?
A Bag<E> is a collection interface that keeps count of how many times each distinct object appears, instead of just storing whether it's present or absent like a Set does.
Calling add() twice with the same value doesn't get rejected the way a Set would reject it; instead the Bag simply increments an internal occurrence counter for that value, retrievable via getCount(Object).
Bag<String> bag = new HashBag<>(); bag.add("apple"); bag.add("apple"); bag.add("orange"); System.out.println(bag.getCount("apple")); // 2 System.out.println(bag.size()); // 3
This makes Bag a natural fit for tallying word frequencies, counting votes, or tracking inventory quantities without wiring up a separate Map<E, Integer> by hand.
More Related questions...