Java集合-----Map详解

时间:2023-03-08 16:35:30

      Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value

  •      Map 中的 key 和  value 都可以是任何引用类型的数据
  •      Map 中的 key 用Set来存放,不允许重复,即同一个,常用String类作为Map的“键”
  •      key 和 value 之间存在单向一对一关系,即通过指定的 key 总能找到唯一的、确定的 value

1.HashMap

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());
}
}
}

   2.Hashtable

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());
}
}
}