Java中HashMap和ArrayList的区别?
在Java中,ArrayList
和HashMap
被用作集合。但我不明白什么情况下应该使用ArrayList
,什么时候应该使用HashMap
。他们两者之间的主要区别是什么?
In Java, ArrayList
and HashMap
are used as collections. But I couldn't understand in which situations we should use ArrayList
and which times to use HashMap
. What is the major difference between both of them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您具体询问的是 ArrayList 和 HashMap,但我认为要完全理解正在发生的事情,您必须了解集合框架。因此,ArrayList 实现了 List 接口,HashMap 实现了 Map 接口。所以真正的问题是你什么时候想使用 List,什么时候想使用 Map。这就是 Java API 文档提供很大帮助的地方。
列表:
地图:
因此,正如其他答案所讨论的那样,列表接口(ArrayList)是使用索引访问的对象的有序集合,非常类似于数组(就 ArrayList 而言,顾名思义,它只是背景,但处理数组的许多细节都为您处理了)。当您想要按排序顺序(添加对象的顺序,或者添加对象时指定的列表中的位置)保存内容时,您可以使用 ArrayList。
另一方面,Map 接受一个对象并将其用作另一个对象(值)的键(索引)。假设您有具有唯一 ID 的对象,并且您知道在某个时刻您将希望通过 ID 访问这些对象,Map 将使您变得非常容易(并且更快/更高效)。 HashMap 实现使用键对象的哈希值来定位它的存储位置,因此不再保证值的顺序。然而,Java API 中的其他类可以提供此功能,例如 LinkedHashMap,它除了使用哈希表来存储键/值对之外,还按照键的添加顺序维护键的列表 (LinkedList),因此您始终可以按照添加顺序再次访问这些项目(如果需要)。
You are asking specifically about ArrayList and HashMap, but I think to fully understand what is going on you have to understand the Collections framework. So an ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.
List:
Map:
So as other answers have discussed, the list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background, but a lot of the details of dealing with the array are handled for you). You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
A Map on the other hand takes one object and uses that as a key (index) to another object (the value). So lets say you have objects which have unique IDs, and you know you are going to want to access these objects by ID at some point, the Map will make this very easy on you (and quicker/more efficient). The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarentee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).
如果您使用
ArrayList
,则必须使用索引(int
类型)访问元素。使用HashMap
,您可以通过其他类型的索引(例如String
)访问它们,这对于
ArrayList来说是不可能的(或者更困难)
。访问 ArrayList 中元素的唯一好方法是通过索引号获取元素。因此,这意味着使用
HashMap
您可以使用您想要的每种类型的键。另一个有用的例子是在游戏中:您有一组图像,并且您想要翻转它们。因此,您编写了一个图像翻转方法,然后存储翻转的结果:
您翻转了一次播放器,然后存储它。您可以使用
BufferedImage
作为HashMap
的键类型来访问BufferedImage
。我希望你能理解我的第二个例子。
If you use an
ArrayList
, you have to access the elements with an index (int
type). With aHashMap
, you can access them by an index of another type (for example, aString
)This is impossible (or much more difficult) with an
ArrayList
. The only good way to access elements in anArrayList
is by getting the elements by their index-number.So, this means that with a
HashMap
you can use every type of key you want.Another helpful example is in a game: you have a set of images, and you want to flip them. So, you write a image-flip method, and then store the flipped results:
You flipped player once, and then store it. You can access a
BufferedImage
with aBufferedImage
as key-type for theHashMap
.I hope you understand my second example.
并不是一个真正的 Java 特定问题。看来你需要一本关于数据结构的“入门书”。尝试谷歌搜索“你应该使用什么数据结构”
试试这个链接 http://www.devx.com/ Tips/Tip/14639
来自链接:
以下是一些将最常用的数据结构与特定需求相匹配的提示。
如果要以键值对的形式访问存储的数据,则哈希表或类似的数据结构是不错的选择。例如,如果您要获取员工的姓名,则结果可以以哈希表的形式作为(名称,值)对返回。但是,如果要返回多个员工的姓名,直接返回哈希表并不是一个好主意。请记住,键必须是唯一的,否则您以前的值将被覆盖。
当您需要顺序甚至随机访问时,这是一个不错的选择。此外,如果数据大小最初未知,和/或将动态增长,则使用列表或向量是合适的。例如,要存储 JDBC ResultSet 的结果,可以使用 java.util.LinkedList。然而,如果您正在寻找可调整大小的数组,请使用 java.util.ArrayList 类。
永远不要低估数组。大多数时候,当我们必须使用对象列表时,我们倾向于考虑使用向量或列表。但是,如果集合的大小已知并且不会改变,则可以将数组视为潜在的数据结构。访问数组元素比访问向量或列表更快。这是显而易见的,因为您所需要的只是一个索引。没有额外的 get 方法调用的开销。
4.组合
有时,最好结合使用上述方法。例如,您可以使用哈希表列表来满足特定需求。
从 JDK 1.2 开始,您还拥有像 java.util.TreeSet 这样的设置类,这对于没有重复项的排序集很有用。这些类最好的事情之一是它们都遵守特定的接口,这样您就不必担心具体细节。例如,看看下面的代码。
Not really a Java specific question. It seems you need a "primer" on data structures. Try googling "What data structure should you use"
Try this link http://www.devx.com/tips/Tip/14639
From the link :
Following are some tips for matching the most commonly used data structures with particular needs.
A hashtable, or similar data structures, are good candidates if the stored data is to be accessed in the form of key-value pairs. For instance, if you were fetching the name of an employee, the result can be returned in the form of a hashtable as a (name, value) pair. However, if you were to return names of multiple employees, returning a hashtable directly would not be a good idea. Remember that the keys have to be unique or your previous value(s) will get overwritten.
This is a good option when you desire sequential or even random access. Also, if data size is unknown initially, and/or is going to grow dynamically, it would be appropriate to use a List or Vector. For instance, to store the results of a JDBC ResultSet, you can use the java.util.LinkedList. Whereas, if you are looking for a resizable array, use the java.util.ArrayList class.
Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.
4.Combinations
Sometimes, it may be best to use a combination of the above approaches. For example, you could use a list of hashtables to suit a particular need.
And from JDK 1.2 onwards, you also have set classes like java.util.TreeSet, which is useful for sorted sets that do not have duplicates. One of the best things about these classes is they all abide by certain interface so that you don't really have to worry about the specifics. For e.g., take a look at the following code.
使用列表来表示值的有序集合。例如,您可能有一个要处理的文件列表。
使用映射(通常是无序的)从键到值的映射。例如,您可能有一个从用户 ID 到该用户详细信息的映射,因此您可以高效地查找仅给定 ID 的详细信息。 (您可以通过仅存储键列表和值列表来实现
Map
接口,但通常会有一个更有效的实现 -HashMap<例如,/code> 在内部使用哈希表来获取摊销 O(1) 键查找。)
Use a list for an ordered collection of just values. For example, you might have a list of files to process.
Use a map for a (usually unordered) mapping from key to value. For example, you might have a map from a user ID to the details of that user, so you can efficiently find the details given just the ID. (You could implement the
Map
interface by just storing a list of keys and a list of values, but generally there'll be a more efficient implementation -HashMap
uses a hash table internally to get amortised O(1) key lookup, for example.)地图与列表。
在映射中,您有键/值对。要访问值,您需要知道密钥。键和值之间存在一种持续存在且不是任意的关系。它们在某种程度上是相关的。示例:一个人的 DNA 是唯一的(密钥),并且一个人的姓名(值)或一个人的 SSN(密钥)和一个人的姓名(值)存在很强的关系。
在列表中,您拥有的只是值(人名),要访问它,您需要知道它在列表中的位置(索引)才能访问它。但是列表中值的位置与其索引之间没有永久的关系,它是任意的。
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.
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.
在使用
ArrayList
和HashMap
之前我们应该考虑以下几点。ArrayList
ArrayList
实现List
接口ArrayList
始终保持元素的插入顺序ArrayList 仅存储值或元素
ArrayList
可以包含重复元素ArrayList
中可以有任意数量的 null 元素get()
方法总是提供O(1)
性能HashMap
HashMap
实现Map
接口HashMap
不维护插入顺序。HashMap
存储键和值对HashMap
不包含重复的键,但包含重复的值。HashMap
中只能有一个 null 键,而HashMap
get()
方法中可以有任意数量的 null 值O(1)
在最好的情况下,O(n)
在最坏的情况下示例:
输出
在上面的输出中我们可以看到
ArrayList
包含重复的null
值,Hashmap
包含重复的null
值,但键不重复。当我们使用某些现有键添加值时,
HashMap
替换新值。参考:https://www.geeksforgeeks.org/difference -java中的arraylist和hashmap之间/
We should consider below point before using
ArrayList
andHashMap
.ArrayList
ArrayList
implementsList
InterfaceArrayList
always maintain the insertion order of the elementsArrayList
only stores value or elementArrayList
can contain duplicate elementsArrayList
ArrayList
get()
method always gives anO(1)
performanceHashMap
HashMap
implementsMap
interfaceHashMap
does not maintain the insertion order.HashMap
stores key and value pairsHashMap
does not contain duplicate keys but contains duplicate values.HashMap
HashMap
get()
method can beO(1)
in the best case andO(n)
in the worst caseExample:
Output
In above output we can see
ArrayList
contains duplicatenull
values andHashmap
contains duplicatenull
value but key is not duplicate.HashMap
replace new value when we add value with some existing key.Reference : https://www.geeksforgeeks.org/difference-between-arraylist-and-hashmap-in-java/