我应该使用哪个 Java 集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21974361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:46:19  来源:igfitidea点击:

Which Java Collection should I use?

javaalgorithmarraylistcollectionshashmap

提问by Tim B

In this question How can I efficiently select a Standard Library container in C++11?is a handy flow chart to use when choosing C++ collections.

在这个问题中,如何在 C++11 中有效地选择标准库容器?是选择 C++ 集合时使用的方便流程图。

I thought that this was a useful resource for people who are not sure which collection they should be using so I tried to find a similar flow chart for Java and was not able to do so.

我认为对于不确定应该使用哪个集合的人来说,这是一个有用的资源,所以我试图为 Java 找到一个类似的流程图,但没有找到。

What resources and "cheat sheets" are available to help people choose the right Collection to use when programming in Java? How do people know what List, Set and Map implementations they should use?

有哪些资源和“备忘单”可以帮助人们在 Java 编程时选择正确的 Collection?人们如何知道他们应该使用哪些 List、Set 和 Map 实现?

采纳答案by Tim B

Since I couldn't find a similar flowchart I decided to make one myself.

由于找不到类似的流程图,我决定自己制作一个。

This flow chart does not try and cover things like synchronized access, thread safety etc or the legacy collections, but it does cover the 3 standard Sets, 3 standard Maps and 2 standard Lists.

此流程图并未尝试涵盖诸如同步访问、线程安全等或遗留集合之类的内容,但它确实涵盖了 3 个标准Set、3 个标准Map和 2 个标准List

enter image description here

在此处输入图片说明

This image was created for this answer and is licensed under a Creative Commons Attribution 4.0 International License.The simplest attribution is by linking to either this question or this answer.

此图像是为此答案创建的,并根据知识共享署名 4.0 国际许可协议获得许可。最简单的归因是链接到这个问题或这个答案。

Other resources

其他资源

Probably the most useful other reference is the following page from the oracle documentation which describes each Collection.

可能最有用的其他参考资料是 oracle 文档中描述每个Collection的以下页面。

HashSet vs TreeSet

HashSet 与 TreeSet

There is a detailed discussion of when to use HashSetor TreeSethere: Hashset vs Treeset

有关于何时使用HashSetTreeSet这里的详细讨论: Hashset vs Treeset

ArrayList vs LinkedList

ArrayList 与 LinkedList

Detailed discussion: When to use LinkedList over ArrayList?

详细讨论:何时使用 LinkedList 而不是 ArrayList?

回答by Honza Zidek

Even simpler picture is here. Intentionally simplified!

更简单的图片在这里。有意简化!

  1. Collectionis anything holding data called "elements" (of the same type). Nothing more specific is assumed.

  2. Listis an indexedcollection of data where each element has an index. Something like the array, but more flexible.

    Data in the list keep the order of insertion.

    Typical operation: get the n-th element.

  3. Setis a bag of elements, each elements just once (the elements are distinguished using their equals()method.

    Data in the set are stored mostly just to know whatdata are there.

    Typical operation: tell if an element is present in the list.

  4. Mapis something like the List, but instead of accessing the elements by their integer index, you access them by their key, which is any object. Like the array in PHP :)

    Data in Map are searchable by their key.

    Typical operaion: get an element by its ID (where ID is of any type, not only intas in case of List).

  1. 集合是任何保存称为“元素”(相同类型)的数据的东西。没有更具体的假设。

  2. 列表是数据的索引集合,其中每个元素都有一个索引。类似于数组的东西,但更灵活。

    列表中的数据保持插入顺序。

    典型操作:获取第 n 个元素。

  3. Set是一个元素包,每个元素只有一次(元素使用它们的equals()方法来区分。

    存储集中的数据主要是为了知道那里有什么数据。

    典型操作:判断一个元素是否存在于列表中。

  4. Map类似于 List,但不是通过整数索引访问元素,而是通过它们的key访问它们,它是任何对象。就像 PHP 中的数组 :)

    Map 中的数据可以通过它们的键进行搜索。

    典型操作:通过其 ID 获取元素(其中 ID 是任何类型,不仅仅是intList 的情况)。

The differences

差异

  • Set and Map: in Set you searchdata by themselves, whilst in Map by their key.

  • List and Map: in List you access element by their intindex (position in List), whilst in Map by their key which os of any type (typically: ID)

  • List and Set: in List the elements are bound by their position and can be duplicate, whilst in Set the elements are just "present" (pr not present) and are unique (in the meaning of equals(), or compareTo()for SortedSet)

  • Set 和 Map:在 Set 中您可以自己搜索数据,而在 Map 中则是通过它们的键

  • List 和 Map:在 List 中,您可以通过它们的int索引(在 List 中的位置)访问元素,而在 Map 中通过它们的键访问任何类型的 os(通常:ID)

  • List 和 Set:在 List 中,元素受它们的位置约束并且可以重复,而在 Set 中元素只是“存在”(pr 不存在)并且是唯一的(在equals(), 或compareTo()for的含义中SortedSet

回答by filip_j

It is simple: if you need to store values with keys mapped to them go for the Map interface, otherwise use List for values which may be duplicated and finally use the Set interface if you don't want duplicated values in your collection.

这很简单:如果您需要存储带有映射到它们的键的值,请使用 Map 接口,否则使用 List 存储可能重复的值,如果您不想在集合中使用重复的值,最后使用 Set 接口。

Here is the complete explanation http://javatutorial.net/choose-the-right-java-collection, including flowchart etc

这是完整的解释http://javatutorial.net/choose-the-right-java-collection,包括流程图等

回答by aliteralmind

Summary of the major non-concurrent, non-synchronized collections

主要非并发、非同步集合的总结

Collection: An interface representing an unordered "bag" of items, called "elements". The "next" element is undefined (random).

Collection:一个接口,表示一个无序的“包”项目,称为“元素”。“下一个”元素未定义(随机)。

  • Set: An interface representing a Collectionwith no duplicates.
    • HashSet: A Setbacked by a Hashtable. Fastest and smallest memory usage, when ordering is unimportant.
    • LinkedHashSet: A HashSetwith the addition of a linked list to associate elements in insertion order. The "next" element is the next-most-recently inserted element.
    • TreeSet: A Setwhere elements are ordered by a Comparator(typically natural ordering). Slowest and largest memory usage, but necessary for comparator-based ordering.
    • EnumSet: An extremely fast and efficient Setcustomized for a single enum type.
  • List: An interface representing a Collectionwhose elements are ordered and each have a numeric index representing its position, where zero is the first element, and (length - 1)is the last.
    • ArrayList: A Listbacked by an array, where the array has a length (called "capacity") that is at least as large as the number of elements (the list's "size"). When size exceeds capacity (when the (capacity + 1)-thelement is added), the array is recreated with a new capacity of (new length * 1.5)--this recreation is fast, since it uses System.arrayCopy(). Deleting and inserting/adding elements requires all neighboring elements (to the right) be shifted into or out of that space. Accessing any element is fast, as it only requires the calculation (element-zero-address + desired-index * element-size)to find it's location. In most situations, an ArrayListis preferred over a LinkedList.
    • LinkedList: A Listbacked by a set of objects, each linked to its "previous" and "next" neighbors. A LinkedListis also a Queueand Deque. Accessing elements is done starting at the first or last element, and traversing until the desired index is reached. Insertion and deletion, once the desired index is reached via traversalis a trivial matter of re-mapping only the immediate-neighbor links to point to the new element or bypass the now-deleted element.
  • Map: An interface representing an Collectionwhere each element has an identifying "key"--each element is a key-value pair.
    • HashMap: A Mapwhere keys are unordered, and backed by a Hashtable.
    • LinkedhashMap: Keys are ordered by insertion order.
    • TreeMap: A Mapwhere keys are ordered by a Comparator(typically natural ordering).
  • Queue: An interface that represents a Collectionwhere elements are, typically, added to one end, and removed from the other (FIFO: first-in, first-out).
  • Stack: An interface that represents a Collectionwhere elements are, typically, both added (pushed) and removed (popped) from the same end (LIFO: last-in, first-out).
  • Deque: Short for "double ended queue", usually pronounced "deck". A linked list that is typically only added to and read from either end (not the middle).
  • Set: 表示Collection没有重复项的接口。
    • HashSet: ASetHashtable. 当排序不重要时,最快和最小的内存使用量。
    • LinkedHashSet:AHashSet加上一个链表,以插入顺序关联元素。“下一个”元素是下一个最近插入的元素。
    • TreeSet: ASet其中元素按 a排序Comparator(通常是自然排序)。最慢和最大的内存使用量,但对于基于比较器的排序是必需的。
    • EnumSetSet为单个枚举类型定制的极其快速和高效。
  • List: 表示 a 的接口,Collection其元素是有序的,每个元素都有一个表示其位置的数字索引,其中零是第一个元素,(length - 1)是最后一个。
    • ArrayList: AList由数组支持,其中数组的长度(称为“容量”)至少与元素数量(列表的“大小”)一样大。当大小超过容量时((capacity + 1)-th添加元素时),将使用新容量重新创建数组 --此重新创建(new length * 1.5)速度很快,因为它使用System.arrayCopy(). 删除和插入/添加元素需要将所有相邻元素(向右)移入或移出该空间。访问任何元素都很快,因为它只需要计算(element-zero-address + desired-index * element-size)来找到它的位置。在大多数情况下, anArrayList优于 a LinkedList
    • LinkedListList由一组对象支持,每个对象都链接到它的“前一个”和“下一个”邻居。ALinkedList也是一个QueueDeque。访问元素从第一个或最后一个元素开始,并遍历直到达到所需的索引。插入和删除,一旦通过遍历达到所需的索引,只需重新映射直接相邻链接以指向新元素或绕过现在删除的元素即可。
  • Map:一个接口,Collection其中每个元素都有一个标识“键”——每个元素都是一个键值对。
    • HashMap: AMap其中键是无序的,并由Hashtable.
    • LinkedhashMap:键按插入顺序排列
    • TreeMap: AMap其中键按 aComparator排序(通常是自然排序)。
  • Queue:一个接口,表示Collection元素通常添加到一端并从另一端删除(FIFO:先进先出)。
  • Stack:一个表示Collectionwhere 元素通常从同一端添加(推送)和删除(弹出)的接口(LIFO:后进先出)。
  • Deque:“双端队列”的缩写,通常发音为“deck”。一个通常只添加到两端(而不是中间)和从中读取的链表。

Basic collection diagrams:

基本集合图:

diagram

图表

Comparing the insertion of an element with an ArrayListand LinkedList:

将元素的插入与ArrayListand 进行比较LinkedList

diagram

图表

回答by Aviral Kumar

Which Java Collection should i use ?

我应该使用哪个 Java 集合?

It depends on what problem you are trying to solve or what requirements you have.

这取决于您要解决什么问题或您有什么要求。

Examples :

例子 :

  1. Do you want the elements to be sorted while storing them ? HashSet
  2. Do you want (Key,Value) pairs to be stored ? HashMap
  3. Do you want the order of elements when inserted to be preserved ? ArrayList, LinkedList
  4. Do you want the Keys in (Key,Value) Pair to be sorted ? - strong text
  5. Do you want to implement a Stack to solve your problem ? - Stack
  6. Do you want to have FIFO(First in First out) access ? - Queue
  7. Do you want only UNIQUE elements to be stored ? - HashSet
  8. Do you want to allow key as "Null" while storing (Key,Value) ? - HashMap
  9. Do you want No NULL values for (Key,Value) pair ? HashTable
  1. 您是否希望在存储元素时对元素进行排序?哈希集
  2. 您想要存储 (Key,Value) 对吗?哈希表
  3. 您是否希望保留插入时元素的顺序?数组列表、链表
  4. 您是否希望对 (Key,Value) Pair 中的键进行排序?- 强文本
  5. 你想实现一个堆栈来解决你的问题吗?-堆栈
  6. 您想拥有 FIFO(先进先出)访问权限吗?-队列
  7. 您是否只想存储 UNIQUE 元素?-哈希集
  8. 你想在存储 (Key,Value) 时允许键为 "Null" 吗?-哈希映射
  9. 你想要 (Key,Value) 对没有 NULL 值吗?哈希表

回答by Aliaksandr Shpak

Common collections, Common collections enter image description here

公共集合, 公共集合 在此处输入图片说明

回答by Basil Bourque

Map

地图

If choosing a Map, I made this table summarizing the features of each of the ten implementations bundled with Java 11.

如果选择Map,我制作了这个表格,总结了与 Java 11 捆绑在一起的十个实现中每一个的特性。

Table of map implementations in Java 11, comparing their features

Java 11 中的地图实现表,比较它们的特性