Junior
What is the difference between List and Set in Java?
sobes.tech AI
Answer from AI
Main differences:
- Order of elements:
Listpreserves the order of insertion.Setdoes not guarantee the order of elements (depends on the specific implementation, for example,LinkedHashSetpreserves insertion order).
- Duplicates:
Listallows storing duplicate elements.Setstores only unique elements.
- Access to elements:
Listprovides access to elements by index.Setdoes not provide direct access to elements by index, access is through an iterator or iteration.
- Performance:
- Search and add operations in
Listwith a large number of elements can be slower than inSet(for example, inHashSet). - Add and remove operations in
Set(for example,HashSet) usually have average constant time complexity.
- Search and add operations in
Example:
// List storing duplicates and preserving order
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple");
System.out.println(list); // Output: [Apple, Banana, Apple]
// Set storing only unique elements
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple");
System.out.println(set); // Output: [Apple, Banana] (order may vary)
Comparison table:
| Aspect | List |
Set |
|---|---|---|
| Order | Preserved | Not guaranteed (depends on implementation) |
| Duplicates | Allowed | Not allowed |
| Access by index | Yes | No |
| Interface | java.util.List |
java.util.Set |
| Typical use | Ordered collections, lists | Unique collections, sets |