1、总体结构
2、特点
2.1、Map接口存储的形式是<K,V>
2.2、LinkedHashMap的底层是哈希表加链表,能保证存取顺序
2.3、HashTable和HashMap的区别是:
<1>、HashTable是线程安全的,KV值不能为null
<2>、HashMap是线程不安全的,KV值可以有null
3、常用的四个方法:
put(), get(), remove(), containsKey()
public static void main(String[] args) {
demo01();
}
//测试map集合的四个常用方法
public static void demo01() {
HashMap<String, Integer> hashMap = new HashMap<>();
//1、put()
hashMap.put("小李",23);
hashMap.put("小张",28);
hashMap.put("小王",14);
System.out.println(hashMap);
//2、get()
Integer integer = hashMap.get("小李");
System.out.println("获取小李的年龄为:"+integer);
//3、containsKey()
boolean b = hashMap.containsKey("小张");
System.out.println("是否包含小张:"+b);
//4、remove()
Integer remove = hashMap.remove("小王");
System.out.println("被移除的小王的年龄是:"+remove);
4、Map集合的遍历方式
<1>通过keySet(),先拿到key,再通过key拿到value
<2>entrySet(),把<K,V>看作一个整体拿出来
4.1通过KeySet()遍历Map集合
public class demoForMap_keySet {
public static void main(String[] args) {
demo01();
}
public static void demo01() {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("小李",23);
hashMap.put("小张",28);
hashMap.put("小王",14);
Set<String> strings = hashMap.keySet();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()){
String key = iterator.next();
Integer value = hashMap.get(key);
System.out.println(key+".."+value);
}
}
}
4.2通过EntrySet()遍历Map集合
public class demoForMap_EntrySet {
public static void main(String[] args) {
demo01();
}
public static void demo01() {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("小李",23);
hashMap.put("小张",28);
hashMap.put("小王",14);
Set<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+".."+value);
}
}
}
4.3、存储第三方元素作为key,为保证Key的唯一性,第三方对象要重写hashCode()和equels()
public class DemoFor_Map_EntrySet {
public static void main(String[] args) {
demo01();
}
public static void demo01() {
HashMap<person, String> hashMap = new HashMap<>();
hashMap.put(new person("张三",23),"上海");
hashMap.put(new person("李四",24),"北京");
hashMap.put(new person("王五",25),"成都");
Set<Map.Entry<person, String>> entries = hashMap.entrySet();
Iterator<Map.Entry<person, String>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<person, String> next = iterator.next();
System.out.println(next.getKey()+next.getValue());
}
}
}
public class person {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
person person = (person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
5、注意点
Map中<K,V>的K唯一,当两个K相同,而V不同时,后来的V会覆盖之气的V
|