What is the fundamental difference between the Set<E>
and List<E>
interfaces?
Lists and tuples are standard Python data types that store values in a sequence. Sets are another standard Python data type that also store values. The major difference is that sets, unlike lists or tuples, cannot have multiple occurrences of the same element and store unordered values.
The usage is purely depends on the requirement: If the requirement is to have only unique values then Set is your best bet as any implementation of Set maintains unique values only. If there is a need to maintain the insertion order irrespective of the duplicity then List is a best option.
ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
List
is an ordered sequence of elements whereas Set
is a distinct list of elements which is unordered (thank you, Quinn Taylor).
List<E>:
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.
Set<E>:
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
Lists of unique elements:
Conform to Java's interface named Set
Can not be accessed by index
Implemented using
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With