Interview Q&A · Java · 7 questions in this topic

Sets: HashSet, LinkedHashSet and TreeSet — Java Interview Q&A

All Java topics

How sets enforce uniqueness, and when to choose HashSet, LinkedHashSet or TreeSet. Part of Collections Framework · 294 questions in the Java bank.

What is a Set?

Answer

A Set is a collection that forbids duplicates, so adding an equal element leaves the set unchanged. Most implementations allow at most one null element. Uniqueness rests on the equals and hashCode contract for hashed sets, or on ordering comparison for sorted sets. A set is unordered unless it is a sorted set such as TreeSet or an insertion-ordered set such as LinkedHashSet.

What are the Set implementations?

Answer

The core general-purpose implementations are HashSet, LinkedHashSet, and TreeSet. HashSet gives fast hashed lookup with no order, LinkedHashSet adds predictable insertion order, and TreeSet keeps elements sorted in a Red-Black tree. Modern Java adds EnumSet for enum types, which is extremely compact and fast, and CopyOnWriteArraySet for concurrent read-heavy sets with snapshot iteration. Choose the implementation from whether you need speed, order, sorting, or thread safety.

HashSet features?

Answer

HashSet is a hash-table implementation of Set backed by a HashMap internally. It offers constant-time average performance for add, remove, and contains when elements spread well across buckets. It makes no ordering guarantee and permits at most one null element. Elements must implement sound hashCode and equals methods, because duplicates and lookups are decided by those two methods.

Example

Example.javajava
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("java");
int n = tags.size();

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits