Junior — Middle
What is the difference between the List and Set interfaces in the context of collections?
sobes.tech AI
Answer from AI
In Java, List and Set are collection interfaces with different properties:
- List — an ordered collection that allows duplicates. Elements have an index, and you can access elements by position.
- Set — a collection without duplicates; the order of elements is not guaranteed (unless using specific implementations like LinkedHashSet).
Example:
List<String> list = new ArrayList<>();
list.add("apple");
list.add("apple"); // duplicates are allowed
Set<String> set = new HashSet<>();
set.add("apple");
set.add("apple"); // second element will not be added
Thus, List is suitable when order matters and duplicates are allowed, while Set is used when you need to store unique elements without repetitions.