Java HashMap 储存自定义对象

时间:2022-08-26 16:08:32
package Map.Demo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapDemo {

	public static void main(String[] args) {
 
	/*
	 * 将学生对象和学生的归属地通过键与值储存到map集合中
	 *  
	 *  
	 */
	HashMap<Students, String> hm=new HashMap<>();
		hm.put(new Students("lisi", 38),"北京");
		hm.put(new Students("zhaoliu", 24),"上海");
		hm.put(new Students("xiaoqiang", 31),"沈阳");
		hm.put(new Students("wangcai", 28),"大连");
		hm.put(new Students("zhaoliu", 24),"铁岭");
		
//		Set<Students> keySet=hm.keySet();
//		Iterator<Students> it=keySet.iterator();
		
		Iterator<Students> it=hm.keySet().iterator();//等于前两句
		
		while(it.hasNext()) {
			Students key=it.next();
			String value=hm.get(key);
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
	} 

}