Lists Sets
Lists Sets
Sets
A Set is an unordered collection of unique elements. This means that no
duplicates are allowed, and the elements can be added to the set in any order.
The Set interface in Java provides several classes that implement it. Some of
the commonly used classes are HashSet, LinkedHashSet, and TreeSet.
HashSet: A HashSet stores elements using a hash table. It provides constant-
time performance for basic operations like add, remove, and contains,
assuming that the hash function distributes the elements evenly among the
buckets.
LinkedHashSet: A LinkedHashSet is similar to a HashSet, but it maintains the
insertion order of the elements.
1|Page
java-collections Sudhakara Rao Chillara
TreeSet: A TreeSet stores elements in a sorted tree structure. It provides
guaranteed log(n) time cost for the basic operations like add, remove, and
contains, where n is the size of the set.
When to Use Lists and Sets
Lists are suitable when you need to store a collection of elements in a specific
order and allow duplicates.
For example, if you are creating a shopping list, you would want to maintain
the order of the items and allow the same item to be added multiple times.
Sets are suitable when you need to store a collection of unique elements and
order is not important.
For example, if you are creating a set of unique email addresses, you would not
want to store duplicates and order is not important.
In some cases, you may need to use both lists and sets in your application. For
example, if you are creating a playlist, you may want to store the songs in a list
to maintain their order, but you may also want to store the unique artists in a
set to avoid duplicates.
2|Page
java-collections Sudhakara Rao Chillara