Web / Apache Commons Collections Interview questions
What is the difference between HashBag and TreeBag?
Both are core Bag implementations, but they trade off ordering guarantees against raw performance in opposite directions.
| HashBag | TreeBag |
| backed by a HashMap | backed by a TreeMap |
| no defined iteration order | iterates in sorted order |
| O(1) average add/remove/getCount | O(log n) add/remove/getCount |
| elements need only equals()/hashCode() | elements must be Comparable or supply a Comparator |
Choose HashBag when you only need occurrence counting and don't care about the order elements come back in - it's the faster default. Choose TreeBag when you specifically need the Bag's contents to iterate in sorted order, such as printing a frequency report alphabetically or numerically.
More Related questions...