Junior
What is the difference between List and Set interfaces in Java?
sobes.tech AI
Answer from AI
The main differences between the List and Set interfaces in Java are as follows:
-
Order of elements:
Listmaintains the order of insertion. Elements have indices starting from 0.Setdoes not guarantee the order of elements. Some implementations may have a specific order (e.g.,LinkedHashSet,TreeSet), but theSetinterface does not require it.
-
Duplicates:
Listallows storing duplicate elements.Setdoes not allow duplicates. When attempting to add a duplicate, the operation is either ignored or returnsfalse(depending on the implementation and method).
-
Performance:
- Add and remove operations in the middle of a
Listcan be slower (especially forArrayList) than in aSet. - Checking for the presence of an element (
contains) in hash-basedSets (HashSet) is usually faster (average O(1)) compared toList(average O(n)). - Index-based operations (e.g.,
get,set) are only available inList.
- Add and remove operations in the middle of a
-
Implementations:
- Common
Listimplementations:ArrayList,LinkedList,Vector. - Common
Setimplementations:HashSet,LinkedHashSet,TreeSet.
- Common
Here are examples demonstrating the differences:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CollectionDifferences {
public static void main(String[] args) {
// List allows duplicates and maintains order
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Added duplicate
System.out.println("List: " + list); // Outputs [Apple, Banana, Apple]
System.out.println("List at index 1: " + list.get(1)); // Access by index
// Set does not allow duplicates and order is not guaranteed (for HashSet)
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Attempt to add duplicate - will be ignored
System.out.println("Set: " + set); // Outputs something like [Apple, Banana] or [Banana, Apple]
// set.get(1); // Compilation error - no access by index
}
}
Comparison table:
| Characteristic | List | Set |
|---|---|---|
| Order | Guaranteed (insertion order) | Not guaranteed (for HashSet, TreeSet has sorted order) |
| Duplicates | Allowed | Not allowed |
| Access by index | Possible (get(int index)) |
Not possible |
| contains() performance | O(n) on average (for ArrayList) | O(1) on average (for HashSet) |
| Typical implementations | ArrayList, LinkedList, Vector | HashSet, LinkedHashSet, TreeSet |