何时在 LinkedList 或 ArrayList 上使用 HashMap,反之亦然 [英] When to use HashMap over LinkedList or ArrayList and vice-versa

查看:27
本文介绍了何时在 LinkedList 或 ArrayList 上使用 HashMap,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能总是使用 HashMap,即使它在添加、删除操作中比 ArrayList 或 LinkedList 高效得多,而且与元素的数量无关.

What is the reason why we cannot always use a HashMap, even though it is much more efficient than ArrayList or LinkedList in add,remove operations, also irrespective of the number of the elements.

我在谷歌上搜索并找到了一些原因,但是使用 HashMap 总是有一种解决方法,而且优势仍然存在.

I googled it and found some reasons, but there was always a workaround for using HashMap, with advantages still alive.

推荐答案

列表表示元素的顺序排列.映射用于表示键/值对的集合.

Lists represent a sequential ordering of elements. Maps are used to represent a collection of key / value pairs.

虽然您可以将地图用作列表,但这样做也有一些明显的缺点.

While you could use a map as a list, there are some definite downsides of doing so.

维持秩序:- 根据定义对列表进行排序.您添加项目,然后您可以按照插入项目的顺序遍历列表.当您将项目添加到 HashMap 时,您不能保证按照您放入项目的相同顺序检索项目. HashMap 的子类(如 LinkedHashMap)将保持顺序,但一般情况下,Map 不能保证顺序.

Maintaining order: - A list by definition is ordered. You add items and then you are able to iterate back through the list in the order that you inserted the items. When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map.

键/值语义:- 映射的目的是根据可用于稍后检索项目的键来存储项目.类似的功能只能在有限的情况下使用列表来实现,其中键恰好是列表中的位置.

Key/Value semantics: - The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.

代码可读性考虑以下示例.

    // Adding to a List
    list.add(myObject);         // adds to the end of the list
    map.put(myKey, myObject);   // sure, you can do this, but what is myKey?
    map.put("1", myObject);     // you could use the position as a key but why?

    // Iterating through the items
    for (Object o : myList)           // nice and easy
    for (Object o : myMap.values())   // more code and the order is not guaranteed

收藏功能通过 Collections 类可以为列表使用一些很棒的实用函数.例如...

Collection functionality Some great utility functions are available for lists via the Collections class. For example ...

    // Randomize the list
    Collections.shuffle(myList);

    // Sort the list
    Collections.sort(myList, myComparator);  

希望能帮到你,

这篇关于何时在 LinkedList 或 ArrayList 上使用 HashMap,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆