Java中HashMap和ArrayList的区别?

发布于 2024-08-24 07:54:09 字数 144 浏览 7 评论 0原文

在Java中,ArrayListHashMap被用作集合。但我不明白什么情况下应该使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

眼中杀气 2024-08-31 07:54:09

您具体询问的是 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:

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

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

友欢 2024-08-31 07:54:09

如果您使用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");

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

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

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

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

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

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

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)

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.

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:

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.

I hope you understand my second example.

云朵有点甜 2024-08-31 07:54:09

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

试试这个链接 http://www.devx.com/ Tips/Tip/14639

来自链接:

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

  1. 何时使用哈希表?

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

  1. 何时使用列表或向量?

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

  1. 什么时候使用数组?

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

4.组合

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

  1. 设置类

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

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

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.

  1. When to use a 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?

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.

  1. When to use Arrays?

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.

  1. Set Classes

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.

  // ...
  List list = new ArrayList();
  list.add(
み零 2024-08-31 07:54:09

使用列表来表示值的有序集合。例如,您可能有一个要处理的文件列表。

使用映射(通常是无序的)从键到值的映射。例如,您可能有一个从用户 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.)

海螺姑娘 2024-08-31 07:54:09

地图与列表。

在映射中,您有键/值对。要访问值,您需要知道密钥。键和值之间存在一种持续存在且不是任意的关系。它们在某种程度上是相关的。示例:一个人的 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.

红尘作伴 2024-08-31 07:54:09

在使用ArrayListHashMap之前我们应该考虑以下几点。

ArrayList

  • java ArrayList 实现 List 接口
  • ArrayList 始终保持元素的插入顺序
  • ArrayList 仅存储值或元素
  • ArrayList 可以包含重复元素
  • ArrayList 中可以有任意数量的 null 元素
  • ArrayList get() 方法总是提供 O(1) 性能

HashMap

  • java HashMap 实现 Map 接口
  • HashMap 不维护插入顺序。
  • HashMap 存储键和值对
  • HashMap 不包含重复的键,但包含重复的值。
  • HashMap 中只能有一个 null 键,而
  • HashMap get() 方法中可以有任意数量的 null 值 O(1) 在最好的情况下,O(n) 在最坏的情况下

示例:

// Importing all utility classes
import java.util.*;

// Main class
class Demo {
    public static void main(String args[]) {
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();

        // Adding values in ArrayList using standard add() method
        list.add("A");
        list.add(null); // Adding first null value
        list.add("C");
        list.add(null); // Adding second null value
        list.add(null); // Adding third null value

        // Printing ArrayList object
        System.out.println("ArrayList: " + list);

        //Creating HashMap object of integer and string type
        HashMap<Integer, String> hm = new HashMap<Integer, String>();

        // Adding value in HashMap using standard put method
        hm.put(1, "A");
        hm.put(2, "B");
        hm.put(null, "C"); // Adding first null key
        hm.put(null, null); // Again adding null key which replace value of first insert null key value
        hm.put(3, null); // Adding second null value with different key

        // Printing the elements of Hashmap
        System.out.println("HashMap: " + hm);
    }
}

输出

ArrayList: [A, null, C, null, null]
HashMap: {null=null, 1=A, 2=B, 3=null}

在上面的输出中我们可以看到 ArrayList 包含重复的 null 值,Hashmap 包含重复的 null 值,但键不重复。
当我们使用某些现有键添加值时,HashMap 替换新值。

参考:https://www.geeksforgeeks.org/difference -java中的arraylist和hashmap之间/

We should consider below point before using ArrayList and HashMap.

ArrayList

  • The java ArrayList implements List Interface
  • ArrayList always maintain the insertion order of the elements
  • ArrayList only stores value or element
  • ArrayList can contain duplicate elements
  • We can have any number of null elements in ArrayList
  • ArrayList get() method always gives an O(1) performance

HashMap

  • The java HashMap implements Map interface
  • HashMap does not maintain the insertion order.
  • HashMap stores key and value pairs
  • HashMap does not contain duplicate keys but contains duplicate values.
  • We can have only one null key and any number of null values in HashMap
  • HashMap get() method can be O(1) in the best case and O(n) in the worst case

Example:

// Importing all utility classes
import java.util.*;

// Main class
class Demo {
    public static void main(String args[]) {
        // Creating ArrayList of string type
        ArrayList<String> list = new ArrayList<String>();

        // Adding values in ArrayList using standard add() method
        list.add("A");
        list.add(null); // Adding first null value
        list.add("C");
        list.add(null); // Adding second null value
        list.add(null); // Adding third null value

        // Printing ArrayList object
        System.out.println("ArrayList: " + list);

        //Creating HashMap object of integer and string type
        HashMap<Integer, String> hm = new HashMap<Integer, String>();

        // Adding value in HashMap using standard put method
        hm.put(1, "A");
        hm.put(2, "B");
        hm.put(null, "C"); // Adding first null key
        hm.put(null, null); // Again adding null key which replace value of first insert null key value
        hm.put(3, null); // Adding second null value with different key

        // Printing the elements of Hashmap
        System.out.println("HashMap: " + hm);
    }
}

Output

ArrayList: [A, null, C, null, null]
HashMap: {null=null, 1=A, 2=B, 3=null}

In above output we can see ArrayList contains duplicate null values and Hashmap contains duplicate null 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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文