首页 > 编程语言 >Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解

时间:2022-11-17 10:38:45浏览次数:40  
标签:map Java Map 子类 System println key put out

前言

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_java


对应的代码如下

public class Map_ {
public static void main(String[] args) {
//Map接口实现类的特点,使用实现类HashMap
//1.Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value(双列元素)
//2.Map中的key和value可以是任何引用类型的数据,会封装到HashMap$Node对象中
//3.Map中的key不允许重复,原因和HashSet一样,前面分析过源码
//4.Map中的value可以重复
//5.Map中的key可以为null,value也可以为null,注意key为null,只能有一个。value为null,可以有多个
//6.常用String类作为Map的key
Map map = new HashMap();
map.put("no1", "张三");
map.put("no2", "张无忌");
map.put("no1", "张三丰");//当有相同的key时,就等价于替换
map.put("no3", "张三丰");//k-v
map.put(null, null); //k-v
map.put(null, "abc");//等价替换
map.put("no5", null);//k-v
map.put("no4", null);
map.put(1, "赵梅");//k-v
map.put(new Object(), "金毛狮王");
System.out.println(map.get(1));//赵梅
System.out.println("map=" + map);
}
}

输出结果如下

赵梅
map={no2=张无忌, null=abc, no1=张三丰, 1=赵梅, no4=null, no3=张三丰, no5=null, java.lang.Object@135fbaa4=金毛狮王}

Map接口特点

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_增强for循环_02


对应的代码如下

@SuppressWarnings({"ALL"})
public class MapSource_ {
public static void main(String[] args) {
Map map = new HashMap();
map.put("no1", "张三");
map.put("no2", "张无忌");
map.put(new Car(),new Person());

//1.k-v 最后是HashMap$Node node = newNode(hash, key, value, null)
//2.k-v 为了方便程序员的遍历,还会创建EntrySet集合,该集合存放的元素的类型Entry,而一个Entry
//对象就有k,v EntrySet<Entry<K,V>> 即: transient Set<Map.Entry<K,V>> entrySet;
//3.entryset中,定义的类型是Map.Entry,但是实际上存放的还是HashMap$Node
//这是因为static class Node<K,V> implements Map.Entry<K,V>
//4.当把HashMap$Node对象,存放到entrySet就方便我们的遍历,因为Map.Entry提供了重要了方法
// K getKey(); V getValue();
Set set = map.entrySet();
System.out.println(set.getClass());//class java.util.HashMap$EntrySet
for (Object obj : set) {
// System.out.println(obj.getClass());//class java.util.HashMap$Node
//为了从HashMap$Node中取出k-v
//1.先做一个向下转型
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "-" + entry.getValue());
}

Set set1 = map.keySet();
System.out.println(set1.getClass());//class java.util.HashMap$KeySet

Collection values = map.values();
System.out.println(values.getClass());//class java.util.HashMap$Values
}
}
class Car{

}
class Person{

}

输出结果如下

class java.util.HashMap$EntrySet
no2-张无忌
no1-张三
[email protected]_.Person@45ee12a7
class java.util.HashMap$KeySet
class java.util.HashMap$Values

我会以代码的形式,把这些方法演示给大家

上代码:
第一个部分:

@Test
public void test1(){
Map map = new HashMap();
//1.Object put(Object key,Object value):将指定的key-value添加到(或修改)当前map对象中
//添加操作
map.put("aa",123);
map.put("BB",456);
map.put("cc",78);
//修改操作
map.put("aa",33);
System.out.println(map);

//2.void putAll(Map m):将m中的所有key-value对存放到当前map中
Map map1 = new HashMap();
map1.put("cc",100);
map1.put("DD",400);
map.putAll(map1);
System.out.println(map);

//3.Object remove(Object key):移除指定key的key-value对,并返回value
map.remove("aa");
System.out.println(map);
//4.void clear():清空当前map中的所有数据
map.clear();
System.out.println(map);
//size()是输出集合中元素的个数
System.out.println(map.size());
}

输出结果:

{aa=33, BB=456, cc=78}
{aa=33, BB=456, cc=100, DD=400}
{BB=456, cc=100, DD=400}
{}
0

第二部分:

@Test
public void test2(){
Map map = new HashMap();
map.put("aa",123);
map.put("BB",456);
map.put("cc",78);
map.put("aa",33);
//5.Object get(Object key):获取指定key对应的value
Object aa = map.get("aa");
System.out.println(aa);

//6.boolean containsKey(Object key):是否包含指定的key
boolean aa1 = map.containsKey("aa");
System.out.println(aa1);

//7.int size():map中key-value的个数
System.out.println(map.size());

//8.boolean isEmpty():判断当前map是否为空
boolean empty = map.isEmpty();
System.out.println(empty);

//9.boolean equals(Object obj):判断当前map和参数对象obj是否相等
Map map1 = new HashMap();
map1.put("aa",123);
map1.put("BB",456);
map1.put("cc",78);
map1.put("aa",33);
boolean ss = map.equals(map1);
System.out.println(ss);
}

输出结果:

33
true
3
false
true

第三部分:

@Test
public void test3(){
Map map = new HashMap();
map.put("aa",123);
map.put("BB",456);
map.put("cc",78);
//遍历操作
//10.Set keySet():返回所有key构成的set集合
Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("****************");
//11.Collection values():返回所有value构成的Collection集合
Collection values = map.values();
for(Object obj:values){
System.out.println(obj);
}
System.out.println("***********************");
//12.Set entrySet():返回所有key-value对构成的Set集合
//遍历方法一:
Set set1 = map.entrySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()){
Object obj = iterator1.next();
//entrySet集合中的元素都是entry
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey()+"=="+entry.getValue());
}
System.out.println("----------");
//方法二:
Set set2 = map.keySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()){
Object next = iterator2.next();
Object obj = map.get(next);
System.out.println(next +"="+obj);
}
}

输出结果:

aa
BB
cc
****************
123
456
78
***********************
aa==123
BB==456
cc==78
----------
aa=123
BB=456
cc=78

Map的六大遍历方式,代码如下

@SuppressWarnings({"all"})
public class MapFor {
public static void main(String[] args) {
Map map = new HashMap();
map.put("aa", 11);
map.put("bb", 22);
map.put("cc", 33);
map.put("dd", 44);
map.put("ee", 55);

//第一组:先取出所有的key,通过key取出对应的value
Set keySet = map.keySet();
//(1)增强for循环
System.out.println("-----------第一种方式-----------");
for (Object key : keySet) {
System.out.println(key + "-" + map.get(key));
}
//(2)迭代器
System.out.println("-----------第二种方式-----------");
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println(key + "-" + map.get(key));
}

//第二组,把所有的values取出
Collection values = map.values();
//这里可以使用所有的Collections使用的遍历方式
//(1) 增强for循环
System.out.println("----取出所有的value 使用增强for----");
for (Object value : values) {
System.out.println(value);
}

//(2)使用迭代器
System.out.println("----取出所有的value 使用迭代器----");
Iterator iterator1 = values.iterator();
while (iterator1.hasNext()) {
Object next = iterator1.next();
System.out.println(next);
}

//第三组:通过EntrySet 来获取k-v
Set entrySet = map.entrySet(); //EntrySet<Map.Entry<K,V>>
//(1)增强for
System.out.println("-----使用EntrySet 的 增强for循环(第三种)-----");
for (Object entry : entrySet) {
//将entry 转成Map.Entry
Map.Entry m = (Map.Entry) entry;
System.out.println(m.getKey() + "-" + m.getValue());
}
//(2)迭代器
System.out.println("-----使用EntrySet 的 增强for循环(第4种)-----");
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()) {
Object next = iterator2.next();
// System.out.println(next.getClass());//HashMap$Node 实现了Map.Entry(getKey,getValue)
//向下转型HashMap$Node
Map.Entry m = (Map.Entry) next;
System.out.println(m.getKey() + "-" + m.getValue());
}
}
}

输出结果如下

-----------第一种方式-----------
aa-11
bb-22
cc-33
dd-44
ee-55
-----------第二种方式-----------
aa-11
bb-22
cc-33
dd-44
ee-55
----取出所有的value 使用增强for----
11
22
33
44
55
----取出所有的value 使用迭代器----
11
22
33
44
55
-----使用EntrySet 的 增强for循环(第三种)-----
aa-11
bb-22
cc-33
dd-44
ee-55
-----使用EntrySet 的 增强for循环(第4种)-----
aa-11
bb-22
cc-33
dd-44
ee-55

HashMap小结

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_java_03


下面是HashMap底层机制和源码剖析

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_Map_04


Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_迭代器_05


具体源码分析如下

public class HashMapSource1 {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put("java", 10);
map.put("php", 10);
map.put("java", 20);
System.out.println("map=" + map);

//解读HashMap源码
//1.执行构造器new HashMap()
//初始化加载因子loadFactor=0.75
//HashMap$Node[] table=null
/*
//2.执行put 调用hash方法,计算key的hash值(h = key.hashCode()) ^ (h >>> 16)
public V put(K key, V value) {k="java",v=10
return putVal(hash(key), key, value, false, true);
}
3.执行putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;//辅助变量
//如果底层的table数组为空,或者length=0,就扩容到16
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//取出hash值对应的table的索引位置的Node,如果为null,就直接把加入的k-v
//创建成一个Node,加入该位置即可
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;//辅助变量
//如果table的索引位置的key的hash值和新的key的hash值相同,
//并且满足(现有的结点的key和准备添加的key是同一个对象||equals返回真)
//就认为不能加入新的k-v
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//如果当前的table的已有的Node,是红黑树,就按照红黑树的方式处理
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {//死循环
if ((e = p.next) == null) {//如果整个链表没有,没有和他相同,就加到链表的最后
p.next = newNode(hash, key, value, null);
//加入后判断当前链表的数目 是否已经到达8个,到8个后,就调用treeifyBin
//进行红黑树的转换
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&//如果在循环条件过程中,发现有相同,就break,就只是替换value
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//替换,key对应的值
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//每增加一个Node,就size++
if (++size > threshold)//如果size大于临界值就扩容
resize();
afterNodeInsertion(evict);
return null;
}

5.关于树化(转成红黑树)
//如果table为null,或者大小还没有到64,暂时不树化,而是进行扩容
//否则才会真正的树化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
*/

}
}

Hashtable底层源码分析如下

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_增强for循环_06


Hashtable分析源码如下

@SuppressWarnings({"all"})
public class HashTableExercise {
public static void main(String[] args) {
Hashtable table = new Hashtable();
// table.put(null, 100);//异常 NullPointerException
// table.put("john", null);//异常 NullPointerException
table.put("john", 100);//ok
table.put("lucy", 100);//ok
table.put("lic", 100);//ok
table.put("lic", 88);//ok
table.put("hello1", 1);
table.put("hello2", 2);
table.put("hello3", 3);
table.put("hello4", 4);
table.put("hello5", 5);
table.put("hello6", 6);
table.put("hello7", 7);
System.out.println(table);

//简单说明一下 Hashtable的底层
//1.底层有数组Hashtable$Entry[] 初始化为11
//2、临界值 threshold 8 =11*0.75
//3、扩容:按照自己的扩容机制来进行即可
//4、执行方法 addEntry(hash, key, value, index); 添加K-V 封装到Entry
//5、当if(count>=threshold)满足时,就进行扩容
//6、 int newCapacity = (oldCapacity << 1) + 1; 扩容到原来的2倍+1

}
}

下面是HashMap和Hashtable的一个对比

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_迭代器_07


Properties类的详解

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_增强for循环_08


对应的代码如下

package com.map_;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
* @author ly
* @version 1.0
*/
public class Properties_ {
public static void main(String[] args) {
//1.Properties 继承了 Hashtable
//2.可以通过k-v 存放数据,当然key 和 value不能为null
Properties properties = new Properties();
// properties.put(null, 100);//抛出空指针异常
// properties.put("abc", null);// 抛出空指针异常
properties.put("john", 100);//k-v
properties.put("lucy", 100);//k-v
properties.put("lic", 100);//k-v
properties.put("lic", 88);//k-v 如果有相同的key,value被替换
System.out.println("properties=" + properties);

//通过k,获取对应的值
System.out.println(properties.get("lic"));//88

//删除
properties.remove("lic");
System.out.println("properties=" + properties);

//修改
properties.put("john", "约翰");
System.out.println("properties=" + properties);
}
}

输出结果如下

properties={john=100, lic=88, lucy=100}
88
properties={john=100, lucy=100}
properties={john=约翰, lucy=100}

总结

Java 中Map接口及其实现子类HashMap,Hashtable,Properties,TreeMap类的详解_java_09


TreeMap类的详解,并且可以实现key的排序

public class TreeMap_ {
public static void main(String[] args) {
//使用默认的构造器,创建TreeMap,是无序的(也没有排序)
/*
要求:按照传入的key的字符串的大小进行排序
*/
// TreeMap treeMap = new TreeMap();
TreeMap treeMap = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//按照传入的key的字符串的大小进行排序 ,从小到大排序
// return ((String) o1).compareTo((String) o2);
//按照传入的key的字符串的大小进行排序 ,从大到小排序
// return ((String) o1).compareTo((String) o2);
//按照key的字符串的长度 从小到大排序
return ((String) o1).length() - ((String) o2).length();
}
});
treeMap.put("jack", "杰克");
treeMap.put("tom", "汤姆");
treeMap.put("kristina", "克瑞斯提诺");
treeMap.put("smith", "史密斯");
System.out.println(treeMap);

//解读源码
/*
1.构造器,把传入的实现了Comparator接口的匿名内部类(对象),传给了TreeMap的comparator
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
2.调用put方法
2.1第一次添加,把k-v封装到Entry对象,放入到root
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check

root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
2.2以后添加
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);//动态绑定到我们的匿名内部类的compare
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果我们遍历过程中,发现准备添加的key,和当前已有的key相等,就不添加
return t.setValue(value);
} while (t != null);
}
*/
}
}

输出结果如下

{tom=汤姆, jack=杰克, smith=史密斯, kristina=克瑞斯提诺}


标签:map,Java,Map,子类,System,println,key,put,out
From: https://blog.51cto.com/u_15880918/5860060

相关文章