📅  最后修改于: 2023-12-03 14:47:25.401000             🧑  作者: Mango
In Java, both Set
and List
are used to store collections of elements. However, they have different characteristics and are suitable for different use cases. In this article, we will explore the similarities and differences between Set
and List
in Java.
A Set
is an unordered collection that does not allow duplicate elements. It is implemented by several classes in Java, such as HashSet
, TreeSet
, and LinkedHashSet
. Here are some key points about Set
:
Set
are unique. If you try to add a duplicate element, it will not be added.Set
is not guaranteed. You cannot access elements by their index.Set
does not provide any specific methods for inserting or removing elements at a specific position.To create a Set
in Java, you can use the following code:
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
A List
is an ordered collection that allows duplicate elements. It is implemented by several classes in Java, such as ArrayList
, LinkedList
, and Vector
. Here are some key points about List
:
List
can be accessed by their index. The order of elements is preserved.List
allows duplicate elements. You can add multiple copies of the same element.List
provides additional methods for inserting or removing elements at a specific index.To create a List
in Java, you can use the following code:
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
| | Set | List |
|-----------------|------------------------|--------------------------|
| Duplicate | Does not allow | Allows |
| Ordering | Unordered | Ordered |
| Access by Index | No | Yes |
| Insertion | No specific method | add(int index, E e)
|
| Removal | No specific method | remove(int index)
|
add(int index, E e)
method.remove(int index)
method.Both Set
and List
have their own strengths and are suitable for different scenarios. If you need a collection with unique elements and order is not important, Set
is a good choice. On the other hand, if you need to maintain the order of elements or allow duplicates, List
is a better option. Choose the appropriate collection based on your specific requirements.