Java Lists、ArrayLists、Maps、Hashmaps、Collections 等之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4131655/
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-14 11:56:12  来源:igfitidea点击:

What is the difference between Lists, ArrayLists, Maps, Hashmaps, Collections etc..?

javadata-structures

提问by lock

I've been using HashMaps since I started programming again in Java without really understanding these Collections thing.

自从我重新开始用 Java 编程以来,我一直在使用 HashMaps,但并没有真正理解这些集合。

Honestly I am not really sure if using HashMaps all the way would be best for me or for production code. Up until now it didn't matter to me as long as I was able to get the data I need the way I called them in PHP (yes, I admit whatever negative thing you are thinking right now) where $this_is_array['this_is_a_string_index']provides so much convenience to recall an array of variables.

老实说,我不确定一直使用 HashMaps 是否最适合我或生产代码。到目前为止,只要我能够以我在 PHP 中调用它们的方式获取我需要的数据(是的,我承认您现在正在思考的任何负面事情),这对我来说并不重要,其中$this_is_array['this_is_a_string_index']提供了很多方便回忆变量数组。

So now, I have been working with java for more than 3 months and came across the Interfaces I specified above and wondered, why are there so many of these things (not to mention, vectors, abstractList {oh well the list goes on...})?

所以现在,我已经使用 java 超过 3 个月了,遇到了我上面指定的接口,想知道为什么有这么多这些东西(更不用说,vectors,abstractList {哦,这个列表还在继续...... .})?

I mean how are they different from each other?

我的意思是他们有什么不同?

And more importantly, what is the best Interface to use in my case?

更重要的是,在我的情况下使用的最佳界面是什么?

采纳答案by Bart Kiers

The API is pretty clear about the differences and/or relations between them:

API 非常清楚它们之间的差异和/或关系:



Collection

收藏

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.

集合层次结构中的根接口。一个集合代表一组对象,称为它的元素。一些集合允许重复元素,而另一些则不允许。有些是有序的,有些是无序的。

http://download.oracle.com/javase/6/docs/api/java/util/Collection.html

http://download.oracle.com/javase/6/docs/api/java/util/Collection.html

List

列表

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

有序集合(也称为序列)。此界面的用户可以精确控制每个元素在列表中的插入位置。用户可以通过它们的整数索引(在列表中的位置)访问元素,并在列表中搜索元素。

http://download.oracle.com/javase/6/docs/api/java/util/List.html

http://download.oracle.com/javase/6/docs/api/java/util/List.html

Set

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

不包含重复元素的集合。更正式地说,集合不包含一对元素 e1 和 e2,使得 e1.equals(e2),并且最多包含一个空元素。正如其名称所暗示的那样,该接口对数学集合抽象进行建模。

http://download.oracle.com/javase/6/docs/api/java/util/Set.html

http://download.oracle.com/javase/6/docs/api/java/util/Set.html

Map

地图

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

将键映射到值的对象。地图不能包含重复的键;每个键最多可以映射到一个值。

http://download.oracle.com/javase/6/docs/api/java/util/Map.html

http://download.oracle.com/javase/6/docs/api/java/util/Map.html



Is there anything in particular you find confusing about the above? If so, please edit your original question. Thanks.

您对上述内容有什么特别困惑的地方吗?如果是这样,请编辑您的原始问题。谢谢。

回答by Andreas Dolk

In Brief (and only looking at interfaces):

简而言之(并且只看接口):

List- a list of values, something like a "resizable array"

List- 值列表,类似于“可调整大小的数组”

Set- a container that does not allow duplicates

Set- 一个不允许重复的容器

Map- a collection of key/value pairs

Map- 键/值对的集合

回答by Tikhon Jelvis

That is a question that ultimately has a very complex answer--there are entire college classes dedicated to data structures. The short answer is that they all have trade-offs in memory usage and the speed of various operations.

这是一个最终有一个非常复杂的答案的问题——整个大学课程都专门研究数据结构。简短的回答是,它们都在内存使用和各种操作的速度方面进行权衡。

What would be really healthy is some time with a nice book on data structures--I can almost guarantee that your code will improve significantly if you get a nice understanding of data structures.

真正健康的是花些时间读一本关于数据结构的好书——我几乎可以保证,如果你对数据结构有很好的理解,你的代码会显着改进。

That said, I can give you some quick, temporaryadvice from my experience with Java. For most simple internal things, ArrayListis generally preferred. For passing collections of data about, simple arrays are generally used. HashMapis only really used for cases when there is some logical reason to have special keys corresponding to values--I haven't seen anyone use them as a general data structure for everything. Other structures are more complicated and tend to be used in special cases.

也就是说,我可以根据我的 Java 经验给你一些快速、临时的建议。对于大多数简单的内部事物,ArrayList通常是首选。为了传递有关的数据集合,通常使用简单的数组。HashMap仅在有某种逻辑原因需要与值对应的特殊键的情况下才真正使用 - 我还没有看到有人将它们用作所有事物的通用数据结构。其他结构更复杂,往往在特殊情况下使用。

回答by darioo

As you already know, they are containers for objects. Reading their respective APIs will help you understand their differences.

如您所知,它们是对象的容器。阅读它们各自的 API 将有助于您了解它们之间的差异。

Since others have described what are their differences about their usage, I will point you to this linkwhich describes complexity of various data structures.

由于其他人已经描述了他们在用法上的差异,我将指向这个链接,它描述了各种数据结构的复杂性。

This list is programming language agnostic, and, as always, real world implementations will vary.

此列表与编程语言无关,并且与往常一样,现实世界的实现会有所不同。

It is useful to understand complexity of various operations for each of these structures, since in the real world, it will matter if you're constantly searching for an object in your 1,000,000 element linked list that's not sorted. Performance will not be optimal.

了解每种结构的各种操作的复杂性很有用,因为在现实世界中,如果您不断在 1,000,000 个元素的链表中搜索未排序的对象,这将很重要。性能不会是最佳的。

回答by MAK

A short summary of common java collections:

常见java集合的简短总结:

'Map': A 'Map' is a container that allows to store key=>value pair. This enables fast searches using the key to get to its associated value. There are two implementations of this in the java.util package, 'HashMap' and 'TreeMap'. The former is implemented as a hastable, while the latter is implemented as a balanced binary search tree(thus also having the property of having the keys sorted).

'Map':'Map' 是一个允许存储键=> 值对的容器。这允许使用键快速搜索以获取其关联值。在 java.util 包中有两个实现,“HashMap”和“TreeMap”。前者实现为hastable,而后者实现为平衡二叉搜索树(因此也具有键排序的特性)。

'Set': A 'Set' is a container that holds only unique elements. Inserting the same value multiple times will still result in the 'Set' only holding one instance of it. It also provides fast operations to search, remove, add, merge and compute the intersection of two sets. Like 'Map' it has two implementations, 'HashSet' and 'TreeSet'.

“Set”:“Set”是一个只包含唯一元素的容器。多次插入相同的值仍会导致 'Set' 只保存它的一个实例。它还提供了快速操作来搜索、删除、添加、合并和计算两个集合的交集。像“Map”一样,它有两个实现,“HashSet”和“TreeSet”。

'List': The 'List' interface is implemented by the 'Vector', 'ArrayList' and 'LinkedList' classes. A 'List' is basically a collection of elements that preserve their relative order. You can add/remove elements to it and access individual elements at any given position. Unlike a 'Map', 'List' items are indexed by an int that is their position is the 'List' (the first element being at position 0 and the last at 'List.size()'-1). 'Vector' and 'ArrayList' are implemented using an array while 'LinkedList', as the name implies, uses a linked list. One thing to note is, unlike php's associative arrays (which are more like a Map), an array in Java and many other languages actually represents a contiguous block of memory. The elements in an array are basically laid out side by side on adjacent "slots" so to speak. This gives very fast lookup and write times, much faster than associative arrays which are implemented using more complex data structures. But they can't be indexed by anything other than the numeric positions within the array, unlike associative arrays.

“List”:“List”接口由“Vector”、“ArrayList”和“LinkedList”类实现。“列表”基本上是保留其相对顺序的元素的集合。您可以向其中添加/删除元素并访问任何给定位置的单个元素。与 'Map' 不同,'List' 项由一个 int 索引,即它们的位置是 'List'(第一个元素在位置 0,最后一个元素在 'List.size()'-1)。'Vector' 和 'ArrayList' 使用数组实现,而 'LinkedList',顾名思义,使用链表。需要注意的一件事是,与 php 的关联数组(它更像是一个Map),Java 和许多其他语言中的数组实际上表示一个连续的内存块。可以这么说,数组中的元素基本上并排布置在相邻的“插槽”上。这提供了非常快的查找和写入时间,比使用更复杂的数据结构实现的关联数组快得多。但与关联数组不同,除了数组中的数字位置之外,它们不能被任何索引。

To get a really good idea of what each collection is good for and their performance characteristics I would recommend getting a good idea about data structures like arrays, linked lists, binary search trees, hashtables, as well as stacks and queues. There is really no substitute to learning this if you want to be an effective programmer in any language.

为了真正了解每个集合的用途及其性能特征,我建议您对数组、链表、二叉搜索树、哈希表以及堆栈和队列等数据结构有一个很好的了解。如果您想成为任何语言的有效程序员,那么学习这一点真的无可替代。

You can also read the Java Collectionstrail to get you started.

您还可以阅读Java Collections跟踪以开始使用。

回答by maxmcbyte

A Map vs a List.

地图与列表。

In a Map, you have key/value pairs. To access a value you need to know the key. There is a relationship that exists between the key and the value that persists and is not arbitrary. They are related somehow. Example: A persons DNA is unique (the key) and a persons name (the value) or a persons SSN (the key) and a persons name (the value) there is a strong relationship.

在 Map 中,您有键/值对。要访问值,您需要知道密钥。键和值之间存在一种持续存在且不是任意的关系。它们以某种方式相关。示例:一个人的 DNA 是唯一的(键)和一个人的名字(值)或一个人的 SSN(键)和一个人的名字(值)有很强的关系。

In a List, all you have are values (a persons name), and to access it you need to know its position in the list (index) to access it. But there is no permanent relationship between the position of the value in the list and its index, it is arbitrary.

在列表中,您拥有的只是值(人名),要访问它,您需要知道它在列表中的位置(索引)才能访问它。但是值在列表中的位置与其索引之间没有永久的关系,它是任意的。

回答by ankit gupta

Difference between Set, List and Map in Java - Set, List and Map are three important interface of Java collection framework and Difference between Set, List and Map in Java is one of the most frequently asked Java Collection interview question. Some time this question is asked as When to use List, Set and Map in Java. Clearly, interviewer is looking to know that whether you are familiar with fundamentals of Java collection framework or not. In order to decide when to use List, Set or Map , you need to know what are these interfaces and what functionality they provide. List in Java provides ordered and indexed collection which may contain duplicates. Set provides an un-ordered collection of unique objects, i.e. Set doesn't allow duplicates, while Map provides a data structure based on key value pair and hashing. All three List, Set and Map are interfaces in Java and there are many concrete implementation of them are available in Collection API. ArrayList and LinkedList are two most popular used List implementation while LinkedHashSet, TreeSet and HashSet are frequently used Set implementation. In this Java article we will see difference between Map, Set and List in Java and learn when to use List, Set or Map.

Java 中 Set、List 和 Map 之间的区别 - Set、List 和 Map 是 Java 集合框架的三个重要接口,Java 中 Set、List 和 Map 之间的区别是 Java Collection 面试中最常见的问题之一。有时这个问题被问到何时在 Java 中使用 List、Set 和 Map。显然,面试官希望知道您是否熟悉 Java 集合框架的基础知识。为了决定何时使用 List、Set 或 Map,您需要知道这些接口是什么以及它们提供了什么功能。Java 中的列表提供了可能包含重复项的有序和索引集合。Set 提供了唯一对象的无序集合,即 Set 不允许重复,而 Map 提供基于键值对和散列的数据结构。所有三个列表,Set 和 Map 是 Java 中的接口,在 Collection API 中有很多具体的实现。ArrayList 和 LinkedList 是两种最常用的 List 实现,而 LinkedHashSet、TreeSet 和 HashSet 是常用的 Set 实现。在这篇 Java 文章中,我们将看到 Java 中 Map、Set 和 List 之间的区别,并了解何时使用 List、Set 或 Map。

Set vs List vs Map in Java

Java 中的 Set vs List vs Map

As I said Set, List and Map are interfaces, which defines core contract e.g. a Set contract says that it can not contain duplicates. Based upon our knowledge of List, Set and Map let's compare them on different metrics.

正如我所说的 Set、List 和 Map 是接口,它们定义了核心合约,例如 Set 合约表示它不能包含重复项。基于我们对 List、Set 和 Map 的了解,让我们在不同的指标上比较它们。

Duplicate Objects Main difference between List and Set interface in Java is that List allows duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract. Map holds two object per Entry e.g. key and value and It may contain duplicate values but keys are always unique. See here for more difference between List and Set data structure in Java.

重复对象 Java 中 List 和 Set 接口的主要区别在于 List 允许重复,而 Set 不允许重复。Set 的所有实现都遵守此合同。Map 每个条目包含两个对象,例如键和值,它可能包含重复的值,但键始终是唯一的。有关 Java 中 List 和 Set 数据结构之间的更多区别,请参见此处。

Order Another key difference between List and Set is that List is an ordered collection, List's contract maintains insertion order or element. Set is an unordered collection, you get no guarantee on which order element will be stored. Though some of the Set implementation e.g. LinkedHashSet maintains order. Also SortedSet and SortedMap e.g. TreeSet and TreeMap maintains a sorting order, imposed by using Comparator or Comparable.

Order List 和 Set 的另一个关键区别是 List 是有序集合,List 的契约维护插入顺序或元素。Set 是一个无序集合,您无法保证将存储哪个 order 元素。尽管某些 Set 实现(例如 LinkedHashSet)保持顺序。还有 SortedSet 和 SortedMap,例如 TreeSet 和 TreeMap 维护一个排序顺序,通过使用 Comparator 或 Comparable 强加。

Null elements List allows null elements and you can have many null objects in a List, because it also allowed duplicates. Set just allow one null element as there is no duplicate permitted while in Map you can have null values and at most one null key. worth noting is that Hashtable doesn't allow null key or values but HashMap allows null values and one null keys. This is also the main difference between these two popular implementation of Map interface, aka HashMap vs Hashtable.

空元素 List 允许空元素,你可以在一个 List 中有许多空对象,因为它也允许重复。设置只允许一个空元素,因为不允许重复,而在 Map 中,您可以有空值和最多一个空键。值得注意的是,Hashtable 不允许空键或空值,但 HashMap 允许空值和一个空键。这也是 Map 接口的这两种流行实现之间的主要区别,也就是 HashMap 与 Hashtable。

Popular implementation

流行的实现

Most popular implementations of List interface in Java are ArrayList, LinkedList and Vector class. ArrayList is more general purpose and provides random access with index, while LinkedList is more suitable for frequently adding and removing elements from List. Vector is synchronized counterpart of ArrayList. On the other hand, most popular implementations of Set interface are HashSet, LinkedHashSet and TreeSet. First one is general purpose Set which is backed by HashMap , see how HashSet works internally in Java for more details. It also doesn't provide any ordering guarantee but LinkedHashSet does provides ordering along with uniqueness offered by Set interface. Third implementation TreeSet is also an implementation of SortedSet interface, hence it keep elements in a sorted order specified by compare() or compareTo() method. Now the last one, most popular implementation of Map interface are HashMap, LinkedHashMap, Hashtable and TreeMap. First one is the non synchronized general purpose Map implementation while Hashtable is its synchronized counterpart, both doesn' provide any ordering guarantee which comes from LinkedHashMap. Just like TreeSet, TreeMap is also a sorted data structure and keeps keys in sorted order.

Java 中最流行的 List 接口实现是 ArrayList、LinkedList 和 Vector 类。ArrayList 更通用,提供带索引的随机访问,而 LinkedList 更适合频繁添加和删除 List 中的元素。Vector 是 ArrayList 的同步对应物。另一方面,Set 接口最流行的实现是 HashSet、LinkedHashSet 和 TreeSet。第一个是由 HashMap 支持的通用 Set,有关详细信息,请参阅 HashSet 在 Java 内部如何工作。它也不提供任何排序​​保证,但 LinkedHashSet 确实提供排序以及 Set 接口提供的唯一性。第三个实现 TreeSet 也是 SortedSet 接口的实现,因此它按照 compare() 或 compareTo() 方法指定的排序顺序保存元素。现在最后一个,Map 接口最流行的实现是 HashMap、LinkedHashMap、Hashtable 和 TreeMap。第一个是非同步的通用 Map 实现,而 Hashtable 是它的同步对应物,两者都不提供来自 LinkedHashMap 的任何排序保证。就像 TreeSet 一样,TreeMap 也是一种排序的数据结构,并按排序顺序保存键。

回答by Hilal Aissani

List Vs Set Vs Map 1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes. Set doesn't allow duplicates. Set and all of the classes which implements Set interface should have unique elements. Map stored the elements as key & value pair. Map doesn't allow duplicate keys while it allows duplicate values.

List Vs Set Vs Map 1) Duplicity:List 允许重复元素。可以将任意数量的重复元素插入到列表中,而不会影响相同的现有值及其索引。Set 不允许重复。Set 和所有实现 Set 接口的类都应该具有唯一的元素。Map 将元素存储为键值对。Map 不允许重复键,但允许重复值。

2) Null values: List allows any number of null values. Set allows single null value at most. Map can have single null key at most and any number of null values.

2) 空值:列表允许任意数量的空值。Set 最多允许单个空值。Map 最多可以有一个空键和任意数量的空值。

3) Order: List and all of its implementation classes maintains the insertion order. Set doesn't maintain any order; still few of its classes sort the elements in an order such as LinkedHashSet maintains the elements in insertion order. Similar to Set Map also doesn't stores the elements in an order, however few of its classes does the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap sorts the elements in the insertion order, the order in which the elements got added to the LinkedHashMap.enter code here

3)顺序:List及其所有实现类维护插入顺序。Set 不维护任何顺序;仍然很少有类按顺序对元素进行排序,例如 LinkedHashSet 以插入顺序维护元素。与 Set Map 类似,也没有按顺序存储元素,但是它的几个类很少这样做。例如,TreeMap 按键的升序对映射进行排序,LinkedHashMap 按插入顺序对元素进行排序,即元素添加到 LinkedHashMap 的顺序。enter code here

回答by Hilal Aissani

List Vs Set Vs Map
1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes.
Set doesn't allow duplicates. Set and all of the classes which implements Set interface should have unique elements.
Map stored the elements as key & value pair. Map doesn't allow duplicate keys while it allows duplicate values.

2) Null values: List allows any number of null values.
Set allows single null value at most.
Map can have single null key at most and any number of null values.

3) Order: List and all of its implementation classes maintains the insertion order.
Set doesn't maintain any order; still few of its classes sort the elements in an order such as LinkedHashSet maintains the elements in insertion order.
Similar to Set Map also doesn't stores the elements in an order, however few of its classes does the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap sorts the elements in the insertion order, the order in which the elements got added to the LinkedHashMap.

回答by Rayen Rejeb

List— An ordered collection of elements that allows duplicate entries

List- 允许重复条目的有序元素集合

Concrete Classes:

具体类:

ArrayList — Standard resizable list.
LinkedList — Can easily add/remove from beginning or end.
Vector — Older thread-safe version of ArrayList.
Stack — Older last-in, first-out class.

ArrayList — 标准的可调整大小的列表。
LinkedList - 可以轻松地从头或尾添加/删除。
Vector — ArrayList 的旧线程安全版本。
堆栈 - 较旧的后进先出类。



Set— Does not allow duplicates

Set- 不允许重复

Concrete Classes:

具体类:

HashSet—Uses hashcode() to find unordered elements.
TreeSet—Sorted and navigable. Does not allow null values.

HashSet——使用 hashcode() 查找无序元素。
TreeSet - 已排序且可导航。不允许空值。



Queue— Orders elements for processing

Queue- 用于处理的订单元素

Concrete Classes:

具体类:

LinkedList — Can easily add/remove from beginning or end.
ArrayDeque—First-in, first-out or last-in, first-out. Does not allow null values.

LinkedList - 可以轻松地从头或尾添加/删除。
ArrayDeque——先进先出或后进先出。不允许空值。



Map— Maps unique keys to values

Map— 将唯一键映射到值

Concrete Classes:

具体类:

HashMap — Uses hashcode() to find keys.
TreeMap — Sorted map. Does not allow null keys.
Hashtable — Older version of hashmap. Does not allow null keys or values.

HashMap — 使用 hashcode() 查找键。
TreeMap — 排序的地图。不允许空键。
Hashtable — 较旧版本的 hashmap。不允许空键或值。