Set vs List in Java: Key Differences Explained
Q: What is the difference between a set and a list in Java? When would you use each one?
- Java
- Senior level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, a set is a collection that contains only unique elements, whereas a list is a collection that can contain duplicate elements. The main difference between the two is that a set enforces uniqueness, whereas a list does not.
Here are some scenarios where you might choose to use a set over a list:
- When you want to ensure that a collection does not contain any duplicates.
- When you want to perform set operations such as union, intersection, or difference.
- When you want to store elements in an order that is determined by their values (e.g., a TreeSet).
And here are some scenarios where you might choose to use a list over a set:
- When you need to preserve the order of elements in the collection.
- When you need to allow duplicate elements in the collection.
- When you need to access elements in the collection by their index.
Here's an example of creating and using a set in Java:
Set<String> names = new HashSet<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("Alice"); // This element is not added because it is a duplicate for (String name : names) { System.out.println(name); } // Output: // Alice // Charlie // Bob
And here's an example of creating and using a list in Java:
List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("Alice"); // This element is added because lists allow duplicates for (String name : names) { System.out.println(name); } // Output: // Alice // Bob // Charlie // Alice


