Java中HashMap和ArrayList的区别?

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

Difference between HashMap and ArrayList in Java?

javacollectionsarraylisthashmap

提问by Venkat

In Java, ArrayListand HashMapare used as collections. But I couldn't understand in which situations we should use ArrayListand which times to use HashMap. What is the major difference between both of them?

在Java中,ArrayListHashMap作为收藏。但我无法理解我们应该在哪些情况下使用ArrayList以及在哪些时间使用HashMap. 它们之间的主要区别是什么?

采纳答案by DaveJohnston

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.

您专门询问 ArrayList 和 HashMap,但我认为要完全了解发生了什么,您必须了解 Collections 框架。因此,ArrayList 实现了 List 接口,而 HashMap 实现了 Map 接口。所以真正的问题是你什么时候想用 List 什么时候用 Map。这是 Java API 文档大有帮助的地方。

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.

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

Map:

地图:

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

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

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).

因此,正如其他答案所讨论的那样,列表接口 (ArrayList) 是您使用索引访问的对象的有序集合,很像数组(就 ArrayList 而言,顾名思义,它只是背景,但是很多处理数组的细节都是为你处理的)。当您想要按排序顺序(添加它们的顺序,或者添加对象时指定的列表中的位置)时,您可以使用 ArrayList。

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).

另一方面, Map 接受一个对象并将其用作另一个对象(值)的键(索引)。因此,假设您拥有具有唯一 ID 的对象,并且您知道在某个时候想要通过 ID 访问这些对象,Map 将使您非常容易(并且更快/更有效)。HashMap 实现使用键对象的哈希值来定位它的存储位置,因此不再保证值的顺序。然而,Java API 中还有其他类可以提供此功能,例如 LinkedHashMap,它不仅使用哈希表来存储键/值对,还按照添加顺序维护键的列表 (LinkedList),因此您始终可以按照添加顺序再次访问这些项目(如果需要)。

回答by Jon Skeet

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 couldimplement the Mapinterface by just storing a list of keys and a list of values, but generally there'll be a more efficient implementation - HashMapuses a hash table internally to get amortised O(1) key lookup, for example.)

将映射用于从键到值的(通常是无序的)映射。例如,您可能有一个从用户 ID 到该用户详细信息的映射,因此您可以有效地找到仅给定 ID 的详细信息。(您可以Map通过仅存储键列表和值列表实现接口,但通常会有更有效的实现 -HashMap例如,在内部使用哈希表来获得分摊的 O(1) 键查找。)

回答by Kannan Ekanath

Not really a Java specific question. It seems you need a "primer" on data structures. Try googling "What data structure should you use"

不是一个真正的Java特定问题。看来您需要有关数据结构的“入门”。尝试谷歌搜索“你应该使用什么数据结构”

Try this link http://www.devx.com/tips/Tip/14639

试试这个链接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.

以下是将最常用的数据结构与特定需求相匹配的一些技巧。

  1. When to use a Hashtable?
  1. 何时使用哈希表?

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.

如果要以键值对的形式访问存储的数据,则哈希表或类似的数据结构是不错的选择。例如,如果您正在获取员工的姓名,则结果可以以哈希表的形式作为(姓名,值)对返回。但是,如果您要返回多个员工的姓名,那么直接返回一个哈希表并不是一个好主意。请记住,键必须是唯一的,否则您之前的值将被覆盖。

  1. When to use a List or Vector?
  1. 何时使用列表或向量?

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.

当您希望顺序访问甚至随机访问时,这是一个不错的选择。此外,如果数据大小最初未知,和/或将动态增长,则使用 List 或 Vector 是合适的。例如,要存储 JDBC ResultSet 的结果,您可以使用 java.util.LinkedList。而如果您正在寻找可调整大小的数组,请使用 java.util.ArrayList 类。

  1. When to use Arrays?
  1. 什么时候使用数组?

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.

永远不要低估数组。大多数时候,当我们必须使用对象列表时,我们倾向于考虑使用向量或列表。但是,如果集合的大小已知且不会改变,则可以将数组视为潜在的数据结构。访问数组元素比访问向量或列表更快。这很明显,因为您只需要一个索引。没有额外的 get 方法调用的开销。

4.Combinations

4.组合

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.

有时,最好结合使用上述方法。例如,您可以使用哈希表列表来满足特定需求。

  1. Set Classes
  1. 设置类

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.

从 JDK 1.2 开始,您还有像 java.util.TreeSet 这样的 set 类,这对于没有重复的排序集合很有用。关于这些类的最好的事情之一是它们都遵守特定的接口,因此您不必真正担心细节。例如,看看下面的代码。

  // ...
  List list = new ArrayList();
  list.add(

回答by Martijn Courteaux

If you use an ArrayList, you have to access the elements with an index (inttype). With a HashMap, you can access them by an index of another type (for example, a String)

如果使用ArrayList,则必须使用索引(int类型)访问元素。使用 a HashMap,您可以通过另一种类型的索引(例如, a String)访问它们

HashMap<String, Book> books = new HashMap<String, Book>();
// String is the type of the index (the key)
// and Book is the type of the elements (the values)
// Like with an arraylist: ArrayList<Book> books = ...;

// Now you have to store the elements with a string key:
books.put("Harry Potter III", new Book("JK Rownling", 456, "Harry Potter"));

// Now you can access the elements by using a String index
Book book = books.get("Harry Potter III");

This is impossible (or much more difficult) with an ArrayList. The only good way to access elements in an ArrayListis by getting the elements by their index-number.

使用ArrayList. 访问 an 中元素的唯一好方法ArrayList是通过它们的索引号获取元素。

So, this means that with a HashMapyou can use every type of key you want.

因此,这意味着HashMap您可以使用a使用您想要的每种类型的密钥。

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:

另一个有用的例子是在游戏中:你有一组图像,你想翻转它们。所以,你写了一个 image-flip 方法,然后存储翻转的结果:

HashMap<BufferedImage, BufferedImage> flipped = new HashMap<BufferedImage, BufferedImage>();
BufferedImage player = ...; // On this image the player walks to the left.
BufferedImage flippedPlayer = flip(player); // On this image the player walks to the right.
flipped.put(player, flippedPlayer);
// Now you can access the flipped instance by doing this:
flipped.get(player);

You flipped player once, and then store it. You can access a BufferedImagewith a BufferedImageas key-type for the HashMap.

您翻转播放器一次,然后将其存储。您可以访问一个BufferedImage具有BufferedImage关键型的HashMap

I hope you understand my second example.

我希望你理解我的第二个例子。

回答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.

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