public static void main(String[] args) {
Map<Integer,String> map=new HashMap<String,String>();
map.put(6, "zhang");
map.put(2, "lee");
map.put(null, null);
map.put(1, "zhao");
//第一种:普通使用,二次取值
System.out.println("\n通过Map.keySet遍历key和value:");
for(Integer key:map.keySet())
{
System.out.println("Key: "+key+" Value: "+map.get(key));
}
//第二种
System.out.println("\n通过Map.entrySet使用iterator遍历key和value: ");
Iterator map1it=map.entrySet().iterator();
while(map1it.hasNext())
{
Map.Entry<Integer, String> entry=(Entry<Integer, String>) map1it.next();
System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("\n通过Map.entrySet遍历key和value");
for(Map.Entry<Integer, String> entry: map.entrySet())
{
System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue());
}
//第四种
System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key");
for(String v:map.values())
{
System.out.println("The value is "+v);
}
}
对应的输出结果
通过Map.keySet遍历key和value:
Key: 1 Value: zhao
Key: 2 Value: lee
Key: 6 Value: zhang
Key: null Value: null
通过Map.entrySet使用iterator遍历key和value:
Key: 1 Value: zhao
Key: 2 Value: lee
Key: 6 Value: zhang
Key: null Value: null
通过Map.entrySet遍历key和value
Key: 1 Value: zhao
Key: 2 Value: lee
Key: 6 Value: zhang
Key: null Value: null
通过Map.values()遍历所有的value,但不能遍历key
The value is zhao
The value is lee
The value is zhang
The value is null
通过此输出我们发现null键值最后输出。
hashCode() 方法得到其 hashCode 值——每个 Java 对象都有 hashCode() 方法,都可通过该方法获得它的 hashCode 值。得到这个对象的 hashCode 值之后,系统会根据该 hashCode 值来决定该元素的存储位置。
一般来说hasmap存的是无序的。