hashmap对象的使用

来源:互联网 发布:西安行知小学地址 编辑:程序博客网 时间:2024/04/29 14:53

1111111111111111111111111111111111111111111111111111111

HashMap获取键和值

// 新建HashMap
HashMap map = new HashMap();
// 添加操作
map.put("one", r.nextInt(10));
map.put("two", r.nextInt(10));
map.put("three", r.nextInt(10));
// 打印出map
System.out.println("map:"+map );
// 通过Iterator遍历key-value
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println("next : "+ entry.getKey() +" - "+entry.getValue());
}
// HashMap的键值对个数 
System.out.println("size:"+map.size());
// containsKey(Object key) :是否包含键key
System.out.println("contains key two : "+map.containsKey("two"));
System.out.println("contains key five : "+map.containsKey("five"));
// containsValue(Object value) :是否包含值value
System.out.println("contains value 0 : "+map.containsValue(new Integer(0)));
// remove(Object key) : 删除键key对应的键值对
map.remove("three");
System.out.println("map:"+map );
// clear() : 清空HashMap
map.clear();
// isEmpty() : HashMap是否为空
System.out.println((map.isEmpty()?"map is empty":"map is not empty") );
2222222222222222222222222222222222222222222222222222222

java集合类HashMap获取键和值

Map<Integer,Integer> map = new HashMap<Integer,Integer>();  //创建一个HashMap  

        for(int i=0;i<10;i++){                       //为HashMap存储键值对  
            map.put(i, i);  
        }  
          
        Set<Integer> keySets = map.keySet();              //获取键 的Set集合  
      
        System.out.print("Map键:");  
        for(Integer keySet:keySets){                    //迭代输出键  
            System.out.print(keySet+" ");  
        } 


Collection<Integer> values = map.values();            //获取HashMap值  
        System.out.print("Map值:");  
        for(Integer value:values){                  //遍历输出HashMap值  
            System.out.print(value+" ");  
        }  


0 0
原创粉丝点击