Skip to content
Sharp

Collections · interview question

When should you prefer a TreeSet over a HashSet for storing product names?

Multiple choiceMediumchapter-4-curatedpremiumcollectionscollection-performance-basics
Choose one answer
Answer and explanation

Correct answer

D. When you need sorted order

Why

TreeSet maintains sorted order based on natural ordering or a custom comparator, making it ideal when the collection needs to be iterated in a specific sorted order.

Test yourself on Collections

A free test with instant, explained results. No account needed.

Start free test
All Collections questions →