Sobes.tech
Junior — Middle

How does the implementation of Set collection differ from ArrayList in Java?

sobes.tech AI

Answer from AI

The main difference between Set and ArrayList collections in Java lies in their behavior and implementation:

  • Set — a collection that does not allow duplicate elements. The order of elements is not guaranteed (for example, in HashSet), although there are implementations with ordering (TreeSet, LinkedHashSet).
  • ArrayList — an ordered list that allows duplicates and preserves the order of insertion.

In terms of implementation:

  • ArrayList is based on an array that dynamically expands when elements are added. It provides quick access by index.
  • HashSet is usually implemented based on HashMap, where elements act as keys. This ensures fast lookup and uniqueness checking.

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