Junior — Middle
What is the difference in behavior of the contains() method when using lists and sets?
sobes.tech AI
Answer from AI
The contains() method in Java is used to check if a collection contains a specific element. Its behavior differs between lists (List) and sets (Set):
-
List.contains() checks for the presence of an element by iterating through the elements in the order they were added. If the element is found, it returns
true. The order matters, and the search can be slower because the list may contain duplicates. -
Set.contains() is usually implemented based on hash tables (e.g.,
HashSet), providing a faster check for the presence of an element (approximately O(1)). Sets do not contain duplicates, so the check is unambiguous.
Summary:
- In lists,
contains()search is linear in time. - In sets, it is fast due to hashing.
Example:
List<String> list = Arrays.asList("apple", "banana", "apple");
Set<String> set = new HashSet<>(list);
boolean inList = list.contains("apple"); // true
boolean inSet = set.contains("apple"); // true
The main difference is performance and the absence of duplicates in sets.