![]() |
VOOZH | about |
In Java Collections, List and Set are two fundamental interfaces used to store groups of objects. Both are part of the Collection Framework, but they differ in how they store, organize, and handle elements. Understanding both helps in choosing the right collection based on application requirements.
A List in Java is an ordered collection that allows duplicate elements and maintains the insertion order of elements. It is part of the Java Collection Framework and provides positional access to elements.
List<String> list = new ArrayList<>();
List Elements: [Java, Spring, Hibernate, Java] Element at index 1: Spring After removal: [Java, Spring, Java]
Explanation:
A Set in Java is a collection that does not allow duplicate elements and is used when uniqueness of data is required. It is part of the Java Collection Framework and does not maintain insertion order in most implementations.
Set<String> set = new HashSet<>();
Set Elements: [Java, Hibernate, Spring] Contains Spring? true After removal: [Java, Spring]
Explanation:
| Feature | List | Set |
|---|---|---|
| Definition | Ordered collection that allows duplicate elements | Collection that stores only unique elements |
| Package | java.util | java.util |
| Duplicates | Allows duplicate elements | Does not allow duplicate elements |
| Order Maintenance | Maintains insertion order | Does not maintain order (except LinkedHashSet) |
| Index Support | Supports index-based access (get, set) | Does not support index-based access |
| Access Method | Elements can be accessed using index | No index-based access, uses iterator |
| Performance | Slower for search operations in some cases | Faster for search operations (especially HashSet) |
| Null Values | Allows multiple null values | Allows only one null value (HashSet) |
| Implementation Classes | ArrayList, LinkedList, Vector | HashSet, LinkedHashSet, TreeSet |
| Usage | Used when order matters and duplicates are allowed | Used when uniqueness is required |