Set vs List in Java – Java中的集合与列表

最后修改: 2022年 10月 3日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll discuss the differences between Set and List in Java with the help of a simple example.

在本教程中,我们将借助一个简单的例子讨论Java中SetList之间的差异

2. Conceptual Difference

2.概念上的差异

Both List and Set are members of Java Collections. However, there are a few important differences:

ListSet都是Java Collection的成员。然而,有几个重要的区别。

  • A List can contain duplicates, but a Set can’t
  • A List will preserve the order of insertion, but a Set may or may not
  • Since insertion order may not be maintained in a Set, it doesn’t allow index-based access as in the List

Please note that there are a few implementations of the Set interface which maintain order, for example, LinkedHashSet.

请注意,有一些Set接口的实现可以保持顺序,例如,LinkedHashSet

3. Code Example

3.代码示例

3.1. Allowing Duplicates

3.1.允许重复

Adding a duplicate item is allowed for a List. However, it isn’t for a Set:

对于List,允许添加一个重复的项目。然而,对于Set来说,这是不允许的。

@Test
public void givenList_whenDuplicates_thenAllowed(){
    List<Integer> integerList = new ArrayList<>();
    integerList.add(2);
    integerList.add(3);
    integerList.add(4);
    integerList.add(4);
    assertEquals(integerList.size(), 4);
}
@Test
public void givenSet_whenDuplicates_thenNotAllowed(){
    Set<Integer> integerSet = new HashSet<>();
    integerSet.add(2);
    integerSet.add(3);
    integerSet.add(4);
    integerSet.add(4);
    assertEquals(integerSet.size(), 3);
}

3.2. Maintaining Insertion Order

3.2.保持插入顺序

A Set maintains order depending on the implementation. For example, a HashSet is not guaranteed to preserve order, but a LinkedHashSet is. Let’s see an example of ordering with LinkedHashSet:

Set会根据实现来维持秩序。例如,HashSet 不能保证保持顺序,但是LinkedHashSet 可以。让我们看看使用 LinkedHashSet 进行排序的例子。

@Test
public void givenSet_whenOrdering_thenMayBeAllowed(){
    Set<Integer> set1 = new LinkedHashSet<>();
    set1.add(2);
    set1.add(3);
    set1.add(4);
    Set<Integer> set2 = new LinkedHashSet<>();
    set2.add(2);
    set2.add(3);
    set2.add(4);
    Assert.assertArrayEquals(set1.toArray(), set2.toArray());
}

Since a Set is not guaranteed to maintain order, it can’t be indexed.

由于Set不能保证维持秩序,所以它不能被索引。

4. Conclusion

4.总结

In this tutorial, we saw the difference between a List and a Set in Java.

在本教程中,我们看到了Java中ListSet之间的区别。

The source code is available over on GitHub.

源代码可在GitHub上获得