[英]Iterator in java.util.Map
Created a simple java application with a Map to store some data and then iterate and print the key value. 使用Map创建了一个简单的Java应用程序来存储一些数据,然后迭代并打印键值。
Map<String,String> myMap = new HashMap<String,String>();
myMap.put("1", "1");
myMap.put("2", "2");
myMap.put("3", "3");
myMap.put("4", "4");
Iterator<String> it1 = myMap.keySet().iterator();
while(it1.hasNext()){
String key = it1.next();
System.out.println("Map key: "+key + " Map Value:"+myMap.get(key));
/* if(key.equals("2")){
myMap.put("1","4");
//myMap.put("4", "4");
}*/
}
Even I tried the change the put method with different combination like 甚至我尝试使用不同的组合来更改put方法
myMap.put("4", "4");
myMap.put("1", "1");
myMap.put("3", "3");
myMap.put("2", "2");
But I couldn't understood why my program always display the first 3 object in descending. 但是我不明白为什么我的程序总是以降序显示前三个对象。 I couldn't trace what sequencing the iterator uses..
我无法跟踪迭代器使用的排序顺序。
Map key: 3 Map Value:3
Map key: 2 Map Value:2
Map key: 1 Map Value:1
Map key: 4 Map Value:4
The order in which you'll receive elements from a HashMap
is not guaranteed. 不能保证您从
HashMap
接收元素的顺序。 The only guarantees that it makes is that every insertion of a duplicate item is rejected (thus, leaving you with a collection of unique items). 这样做的唯一保证是,每次插入重复项都会被拒绝(因此,您将获得一系列唯一项)。
If you want both guarantees, you'll want to use a LinkedHashMap
instead, which guarantees insertion order. 如果您同时需要两个保证,则需要使用
LinkedHashMap
来保证插入顺序。
HashMap does not gurantee ordering of elements HashMap不保证元素的顺序
Use LinkedHashMap(entry order) or TreeMap (sorted order) if ordering is requrired. 如果需要重新排序,请使用LinkedHashMap(输入顺序)或TreeMap(排序顺序) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.