标签:ack value 关系 practise tab 引用 类型 指定 rac
Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value
HashMap是线程不安全的
package com.gather; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class HashMapPractise { public static void main(String[] args) { Map<String, Person> map = new HashMap<>(); Person p1 = new Person("张三", 22); Person p2 = new Person("李四", 23); Person p3 = new Person("王五", 22); map.put("AA", p1); map.put("BB", p2); map.put("CC", p3); //第一种遍历方式:能同时取出键值对 for(String str:map.keySet()) { System.out.println("键为:"+str+",值为:"+map.get(str)); } System.out.println("------------------------------"); //第二种遍历方式:只取值或只取键 for(String str:map.keySet()) { System.out.println("键为:"+str); } for(Person person:map.values()) { System.out.println("值为:"+person); } System.out.println("------------------------------"); //推荐:第三种遍历方式:能同时取出键值对 for(Entry<String,Person> entry:map.entrySet()) { System.out.println("键为:"+entry.getKey()+",值为:"+entry.getValue()); } System.out.println("------------------------------"); //第四种遍历方式:能同时取出键值对 Iterator<Entry<String, Person>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Entry<String, Person> entry = entries.next(); System.out.println("键为:"+entry.getKey()+",值为:"+entry.getValue()); } } }
Hashtable是线程安全的
package com.gather; import java.util.Enumeration; import java.util.Hashtable; import java.util.Map; import java.util.Map.Entry; public class HashtablePractise { public static void main(String[] args) { Map<String, Person> map = new Hashtable<>(); Person p1 = new Person("张三", 22); Person p2 = new Person("李四", 23); map.put("AA", p1); map.put("BB", p2); for (Entry<String, Person> entry : map.entrySet()) { System.out.println("键为:" + entry.getKey() + ",值为:" + entry.getValue()); } System.out.println("------------------------------"); Hashtable<String, Person> hashtable = new Hashtable<>(); hashtable.put("AA", p1); hashtable.put("BB", p2); // Hashtable的另外一种遍历方式:Enumeration Enumeration<String> enuKey = hashtable.keys(); while (enuKey.hasMoreElements()) { System.out.println(enuKey.nextElement()); } Enumeration<Person> enuValue = hashtable.elements(); while (enuValue.hasMoreElements()) { System.out.println(enuValue.nextElement()); } } }
标签:ack value 关系 practise tab 引用 类型 指定 rac
原文地址:https://www.cnblogs.com/fengfuwanliu/p/10430915.html