package demo1; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /* * HashMap存储自定义类型的键值 * Map集合保证key是唯一的: * 作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一 * HashMap存储自定义类型的键 * key:Person类型 * Person类就必须重写hashCode方法和equals方法,以保证key唯一 * value:String类型 * 可以重复 */ public class DemoHashMap { public static void main(String[] args) { // show01(); show2(); } public static void show01(){ //创建HashMap集合 HashMap<String,Person> map = new HashMap<>(); //往集合中添加元素 map.put("北京",new Person("wanggang",23)); map.put("上海",new Person("liushishi",23)); map.put("安徽",new Person("liushishi",23)); Set<String> set = map.keySet(); for (String s : set) { // System.out.println(s); Person value = map.get(s); System.out.println(value); } } public static void show2(){ //创建HashMap集合 HashMap<Person,String> map1 = new HashMap<>(); map1.put(new Person("wanggang",23),"北京"); map1.put(new Person("wanggang",23),"北京"); map1.put(new Person("liushishi",23),"上海"); map1.put(new Person("liushishi",23),"深圳"); Set<Map.Entry<Person,String>> map1_itent = map1.entrySet(); // Iterator ma1_iterator = map1_itent.iterator(); // while (ma1_iterator.hasNext()){ // System.out.println(ma1_iterator.next()); // } for (Map.Entry<Person, String> personStringEntry : map1_itent) { Person key = personStringEntry.getKey(); System.out.println(key); } } }
Java 基础 HashMap存储自定义类型键值
最新推荐文章于 2023-11-23 08:41:07 发布