【问题标题】:What is LinkedHashMap and what is it used for?什么是 LinkedHashMap,它的用途是什么?
【发布时间】:2014-08-18 06:31:09
【问题描述】:
当我浏览一个包含 ListViews 的示例代码时,我想到了LinkedHashMap。
什么是LinkedHashMap,我们可以在哪里使用它以及如何使用它?我浏览了几篇文章,但没有完全理解。创建ListView时是否需要。 ListViews 和 LinkedHashMaps 之间有什么联系?谢谢。
【问题讨论】:
标签:
java
android
listview
linkedhashmap
【解决方案1】:
为了简单,让我们了解一下HashMap和LinkedHashMap有什么区别。
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】:
文档在这里。但它基本上是一个 HashMap,它也有一个链表,所以你可以通过它进行一致有序的迭代。请注意,这意味着删除可能需要 O(n) 时间,因为您需要从两个数据结构中删除它。
【解决方案3】:
LinkedHashMap 是哈希图。但它保持插入顺序。但是 HashMap 不维护秩序。
【解决方案4】:
Hi Linked Hash Map 是一个存储键值对的 Map,
Linked Hash Map 添加值可能会很慢,但是在检索值时非常容易。
为了快速检索值,我们可能更喜欢 Linked Hash Map。