例子一:
import java.util.Map; import java.util.Set; import java.util.HashMap; public class HashMapDemo1 { public static void main(String args[]){ User user1 = new User("001","Jack",12); User user2 = new User("002","Marry",13); User user3 = new User("003","Xiaoming",14); User user4 = new User("004","Xiaofang",15); HashMap one= new HashMap(); one.put(user1.getId(),user1); one.put(user2.getId(),user2); one.put(user3.getId(),user3); one.put(user4.getId(),user4); //键值对的个数 System.out.println(one.size()); //直接打印Map对象会打印Key的toString= value的toString System.out.println(one); //Key和value都是Object User user = (User)one.get("002"); System.out.println(user); //是否包含某个key System.out.println(one.containsKey("122")); //遍历 //遍历方法一 把Map集合中所有的Key都放入set集合中 /*然后遍历set集合,得到Key,通过key获取value * */ Set set = one.keySet(); for(Object object: set){ String key = (String)object; User u = (User)one.get(key); System.out.println(key+" = "+u); } System.out.println("====================="); //放入HashMap集合中的key,value其实都会被包装成 /*Map.Entry这个内部色属性 * 有一个键值对就存在一个Map.Entry的实例对象 * 通过entrySet()方法就可以把这些实例对象都放在Set集合中 * 遍历Set获取每个对象 * */ Set set1 = one.entrySet(); for(Object object:set1){ Map.Entry me = (Map.Entry)object; System.out.println(me.getKey()+" = "+me.getValue()); } } }
package corelesson; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapDemo2 { public static void main(String[] args){ User u1 = new User("001","zhang",20); User u2 = new User("002","xiaoming",21); User u3 = new User("003","nihao",23); HashMap<String ,User>users = new HashMap<String,User>(); users.put(u1.getId(),u1); users.put(u2.getId(),u2); users.put(u3.getId(),u3); Set<String> set = users.keySet(); for(String key:set){ System.out.println(key+"=="+users.get(key)); } System.out.println("+++++++++++++++++++++++++++"); Set<Map.Entry<String, User>> set1 = users.entrySet(); for(Map.Entry<String, User> me : set1){ System.out.println(me.getKey()+" = "+me.getValue()); } } }
package corelesson; import java.util.HashMap; public class HashMapDemo3 { public static void main(String[] args){ HashMap<String,Integer> hm = new HashMap<String,Integer>(); hm.put("x", 10); hm.put("y", 20); hm.put("x", 30); //key相同 会覆盖之前的value key如何才能相同 /*注意equals和方法的实现和hashCode方法的实现 * * */ System.out.println(hm); System.out.println("====================="); //计算每个字符出现的次数 String s = "abcdafdfdfdasfdfgrgfrgsafgrgtads"; /* * 思路:拿到每个字符,作为key放入HashMap如果 * 如果map中不存在 那么put(key,1); * 如果已经存在 那么put(key,value+1) * * */ HashMap<String,Integer> hm1 = new HashMap<String,Integer>(); for(int i = 0;i<s.length();i++){ String str = s.substring(i,i+1); if(hm1.containsKey(str)){ hm1.put(str,hm1.get(str)+1); } else{ hm1.put(str, 1); } } System.out.println(hm1); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wei_chong_chong/article/details/47205649