何时使用HashMap的过度LinkedList的或ArrayList和反之亦然 [英] When to use HashMap over LinkedList or ArrayList and vice-versa

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

问题描述

什么是为什么我们不能总是用一个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.

我GOOGLE了一下,发现一些原因,但总有使用HashMap的解决方法,以优势还活着。

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

推荐答案

列出重新present元素的顺序排序。
地图是用来重新present键/值对的集合。

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中,将维持秩序,但一般为了不与地图保证。

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.

code可读性
考虑下面的例子。

Code readability Consider the following examples.

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

希望这有助于

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

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