Differences between List and Set interface in java
Property |
java.util.List |
java.util.Set |
|
1- |
Insertion order |
java.util.List is ordered collection it maintain insertion order in java. |
Most of the java.util.Set implementation does not maintain insertion order. HashSet does not maintains insertion order in java.
TreeSet is sorted by natural order in java. |
2- |
Duplicate elements |
List allows to store duplicate elements in java. |
Set does not allow to store duplicate elements in java. |
3 |
Null keys |
List allows to store many null keys in java. |
Most of the Set implementations allow to add only one null in java. TreeSet does not allow to add null in java. |
4- |
Getting element on specific index |
List implementations provide get method to get element on specific index in java. ArrayList, Vector, copyOnWriteArrayList and LinkedList provides - get(int index) Method returns element on specified index. Get method directly gets element on specified index. Hence, offering O(1) complexity. |
Set implementations does not provide any such get method to get element on specified index in java. |
5- |
Implementing classes |
ArrayList, LinkedList, Vector, CopyOnWriteArrayList classes implements List interface in java. |
HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet, EnumSet classes implements Set interface in java. |
6- |
listIterator |
listIterator method returns listIterator to iterate over elements in List in java. listIterator provides additional methods as compared to iterator like hasPrevious(), previous(), nextIndex(), previousIndex(), add(E element), set(E element) |
Set does not provide anything like listIterator. It simply return Iterator in java. |
7- |
Structure and resizable |
List are Resizable-array implementation of the java.util.List interface in java. |
Set uses Map for their implementation. Hence, structure is map based and resizing depends on Map implementation. |
8- |
Index based structure /RandomAccess |
As ArrayList uses array for implementation it is index based structure, hence provides random access to elements. But LinkedList is not indexed based structure in java. |
Set is not index based structure at all in java. |
post a comment