In this post, we will discuss the difference between List and Set interface in Java.
Set interface are members of the Java Collections Framework. In this post, we will provide an overview of some of the major differences between these two interfaces –
Listin Java represents an ordered sequence of elements and its elements can accessible by index.
Setin Java represents a distinct collection of elements which can be either ordered or unordered, depending on the implementation. For example,
HashSetimplementation is unordered,
LinkedHashSetimplementation is ordered, and
TreeSetimplementation is ordered by natural order or by provided comparator.
- Another notable difference between
Setinterface is that the
Setcontains only distinct elements whereas
Listallows duplicate elements.
Listallows any number of null values while a
Setcan contain at most one null element.
RandomAccessinterface which is a marker interface to support constant time random access. On the other hand, none of the
Setimplementations can implement the
Listinterface provides a special iterator
ListIteratorto facilitate bidirectional access which is not available for
Listshould be used when insertion order of elements needs to maintained. Use a
Setif we need to maintain a collection that contains no duplicate element.
- Popular implementation of
LinkedListwhile that of
Thanks for reading.
Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂