Last Updated: 22 October, 2023
List and Set are both interfaces in the Java Collections framework. Both are available in the java.util package and extend Collection Interface.
List and Set are both used to represent collections of objects, but they have some key differences.
A List is an interface that extends the Collection interface. List was introduced in the JDK 1.2 version and is available in the java.util package.
A List is an ordered collection of elements that allows us to store and access elements sequentially. We can also insert null and duplicate elements in the list.
Since List preserves the insertion order, it also allows positional access, insertion, deletion, and updating of elements.
The List interface is implemented by the ArrayList, LinkedList, Vectors, and Stack classes in Java.
Java List Interface Declaration
Here, E defines the type of elements that the List will contain.
Java List interface important features:
The Set interface in Java is part of the Java Collections Framework. It extends the Collection interface. Set was introduced in the JDK 1.2 version and is available in the java.util package.
The Set Interface is an unordered collection of objects that does not allow the insertion of duplicate elements into the Set.
The Set interface inherits the Collection interface's methods and adds a feature that restricts the insertion of duplicate elements.
The set interface is used to create the mathematical set.
The Set interface is implemented by the HashSet, LinkedHashSet, and TreeSet classes in Java.
There are two interfaces that extend the Set Interface implementation: SortedSet and NavigableSet
Java Set Interface Declaration
Here, E defines the type of elements that the List will contain.
List | Set |
---|---|
A List is an ordered collection of elements. | A Set is an unordered collection of elements. |
List contains duplicate elements. | Set does not contain duplicate elements. |
List accepts any number of nulls as an element. | Set accepts only one null as an element. |
List allows positional access to elements. | Set does not allow positional access to elements. |
List has one legacy class called Vector. | Set does not have any legacy classes. |
List uses ListIterator for traversing the elements in any direction. | ListIterator does not work with Set. |
List implementation classes are ArrayList, LinkedList, Vector, and Stack. | Set implementation classes are TreeSet, HashSet, and LinkedHashSet. |
Output
List Elements: [India, Canada, US, England]
Output
Elements: [800, null, 500, 200]
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com