Java中的HashMap和ArrayList之间的区别?

时间:2023-01-21 16:44:21

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?

在Java中,ArrayList和HashMap用作集合。但我无法理解在哪种情况下我们应该使用ArrayList以及哪些时候使用HashMap。两者之间的主要区别是什么?

5 个解决方案

#1


73  

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的内容,但我认为要完全理解您需要了解的集合框架。因此,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,以及使用哈希表来存储键/值对,还按照添加顺序维护键的List(LinkedList),因此您可以按照添加的顺序再次访问项目(如果需要的话)。

#2


16  

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

如果使用ArrayList,则必须使用索引(int类型)访问元素。使用HashMap,您可以通过另一种类型的索引(例如,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 ArrayList is by getting the elements by their index-number.

使用ArrayList这是不可能的(或者更困难)。访问ArrayList中元素的唯一好方法是通过索引号获取元素。

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

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

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:

另一个有用的例子是游戏:你有一组图像,你想要翻转它们。因此,您编写了一个图像翻转方法,然后存储翻转结果:

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 BufferedImage with a BufferedImage as key-type for the HashMap.

你翻转了一次播放器,然后存储它。您可以使用BufferedImage作为HashMap的键类型来访问BufferedImage。

I hope you understand my second example.

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

#3


14  

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?
  2. 何时使用Hashtable?

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?
  2. 何时使用List或Vector?

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?
  2. 何时使用数组?

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

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

  1. Set Classes
  2. 设置类

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,这对于没有重复项的排序集非常有用。这些课程最好的一点是他们都遵守某些界面,所以你不必担心具体细节。例如,请查看以下代码。

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

#4


4  

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

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

#5


4  

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.

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

#1


73  

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的内容,但我认为要完全理解您需要了解的集合框架。因此,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,以及使用哈希表来存储键/值对,还按照添加顺序维护键的List(LinkedList),因此您可以按照添加的顺序再次访问项目(如果需要的话)。

#2


16  

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

如果使用ArrayList,则必须使用索引(int类型)访问元素。使用HashMap,您可以通过另一种类型的索引(例如,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 ArrayList is by getting the elements by their index-number.

使用ArrayList这是不可能的(或者更困难)。访问ArrayList中元素的唯一好方法是通过索引号获取元素。

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

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

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:

另一个有用的例子是游戏:你有一组图像,你想要翻转它们。因此,您编写了一个图像翻转方法,然后存储翻转结果:

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 BufferedImage with a BufferedImage as key-type for the HashMap.

你翻转了一次播放器,然后存储它。您可以使用BufferedImage作为HashMap的键类型来访问BufferedImage。

I hope you understand my second example.

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

#3


14  

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?
  2. 何时使用Hashtable?

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?
  2. 何时使用List或Vector?

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?
  2. 何时使用数组?

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

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

  1. Set Classes
  2. 设置类

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,这对于没有重复项的排序集非常有用。这些课程最好的一点是他们都遵守某些界面,所以你不必担心具体细节。例如,请查看以下代码。

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

#4


4  

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

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

#5


4  

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.

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