What is the fundamental difference between the Set<E> and List<E> interfaces?
26 Answers
List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered (thank you, Quinn Taylor).
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
| List | Set | |
|---|---|---|
| Duplicates | Yes | No |
| Order | Ordered | Depends on implementation |
| Position Access | Yes | No |
Ordered lists of element (unique or not)
Conform to Java's interface named List
Can be accessed by index
Implemented using
- LinkedList
- ArrayList
Lists of unique elements:
Conform to Java's interface named Set
Can not be accessed by index
Implemented using
- HashSet (unordered)
- LinkedHashSet (ordered)
- TreeSet (sorted by natural order or by provided comparator)
Both interfaces Set and List conform to Java's interface named Collection
A Set cannot contain duplicate elements while a List can. A List (in Java) also implies order.
- A List is an ordered grouping of items
- A Set is an unordered grouping of items with no duplicates allowed (usually)
Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn't allow duplicates is a Set.
List:
Lists generally allow duplicate objects.
Lists must be ordered, and are therefore accessible by index.
Implementation classes include: ArrayList, LinkedList, Vector