Difference Between List and Set in Java
Feature | List | Set |
Definition | An ordered collection of elements. | An unordered collection of unique elements. |
Duplicates | Allows duplicate elements. | Does not allow duplicate elements. |
Ordering | Maintains the insertion order. | Does not guarantee order (unless using LinkedHashSet or TreeSet). |
Access | Access elements by index using get(). | Does not support access by index. |
Implementations | ArrayList, LinkedList, Vector. | HashSet, LinkedHashSet, TreeSet. |
Summary:
- Use List when duplicates and element order matter.
- Use Set when unique elements are required, and order is not a priority.