set是无序集合,放入set中的元素通过iterator输出时候是无序的
HashMap<String , String> hashMap = new HashMap<String , String>(); for (int i = 0; i < 100; i++) { hashMap.put(i+"", i+"a"); } Set<Entry<String, String>> entry = hashMap.entrySet(); Iterator<Entry<String, String>> entryIterator = entry.iterator(); while(entryIterator.hasNext()) { Map.Entry<String, String> entryItem = entryIterator.next(); System.out.println(entryItem.getKey()+":"+entryItem.getValue()); }
输出结果:是乱序的
88:88a 89:89a 90:90a 91:91a 92:92a 93:93a 94:94a 95:95a 96:96a 97:97a 10:10a 98:98a 11:11a 99:99a 12:12a 13:13a 14:14a 15:15a 16:16a 17:17a 18:18a 19:19a 0:0a 1:1a 2:2a 3:3a 4:4a 5:5a 6:6a 7:7a 8:8a 9:9a 20:20a 21:21a 22:22a 23:23a 24:24a 25:25a 26:26a
1.hashmap遍历方法:
Set ss=hm.entrySet() ;//返回Map.Entry 接口实现
printElements(ss); //输出键值对 利用迭代器
Iterator i=ss.iterator() ; //通过 Map.Entry静态接口 获取元素
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next() ;//强制转换
System.out.println(me.getKey()+":"+me.getValue());
}