LinkedHashMap是什么,它有什么用途?

4

当我在查阅关于ListView的示例代码时,我遇到了LinkedHashMap。LinkedHashMap是什么,我们可以在哪里使用它,以及如何使用它?我查阅了几篇文章,但并没有完全理解。创建ListView时是否必须使用LinkedHashMap?ListViews和LinkedHashMaps之间有什么联系呢?谢谢。


6
好的,我会尽力进行翻译。以下是您需要翻译的内容:We can tell you, but it's always better when you read the docs。我们可以告诉你,但当你阅读文档时会更好。 - Nir Alfasi
1
这里也有Android文档 - Michael Shrestha
4个回答

3
为了简单起见,让我们了解一下HashMapLinkedHashMap之间的区别。 HashMap:它以随机顺序输出结果,这意味着我们插入值的顺序没有规律。
LinkedHashMap:它以顺序输出结果。
让我们看一个小例子:使用HashMap。
    // suppose we have written a program
    .
    .
    // now use HashMap
    HashMap map = new HashMap();  // create object
    map.put(1,"Rohit");          // insert values
    map.put(2,"Rahul");
    map.put(3,"Ajay");

    System.out.println("MAP=" +map); //print the output using concatenation


    //So the output may be in any order like we can say the output may be as:
    Map={3=Ajay,2=Rahul,1=Rohit}

但是在LinkedHashMap中情况并非如此。只需将上述代码中的“HashMap”替换为“LinkedHashMap”,然后查看结果,它将按顺序显示输出,例如1=Rohit将首先显示,然后按顺序显示其他内容。


2
文档在这里。但实际上它基本上是一个哈希表,还有一个链表,所以你可以通过它进行一致有序的迭代。请注意,这意味着删除可能需要 O(n) 的时间,因为您需要从两个数据结构中删除它。

1
LinkedHashMap是哈希表,但它保持插入顺序。而HashMap不保持顺序。

1
Linked Hash Map 是一种存储键值对的 Map,添加值可能会比较慢,但检索值非常容易。为了快速检索值,我们可以选择 Linked Hash Map。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接