Junior — Middle
Milline on erinevus Java kogumite Set ja ArrayList kogumite rakendamisel?
sobes.tech AI
Vastus AI-lt
The main difference between the collections Set and ArrayList in Java lies in their behavior and implementation:
- Set — is a collection that does not allow duplicates. The order of elements is not guaranteed (for example, in HashSet), although there are implementations with ordering (TreeSet, LinkedHashSet).
- ArrayList — is an ordered list that allows duplicates and preserves the insertion order.
From an implementation perspective:
- ArrayList is based on an array that dynamically expands when elements are added. Fast access by index.
- HashSet is usually implemented on top of HashMap, where elements act as keys. This ensures fast search and uniqueness check.
Example:
Set<String> set = new HashSet<>();
set.add("apple");
set.add("apple"); // will not be added a second time
List<String> list = new ArrayList<>();
list.add("apple");
list.add("apple"); // both elements will be added