HashMap 与 HashTable 的 区别

package com.demo.main;

import java.util.HashMap;
import java.util.Hashtable;

public class Main {

	public static void main(String[] args) {

		
		//HashMap 与 HashTable 的 区别 。 
		/*
		 * 1.HashMap线程不安全,HashTable安全。
		 * 2.HashMap的键与值都可以为null,HashTable的键与值都不可以为null。
		 */
		HashMap<String,Integer> hm = new HashMap<>();
		hm.put(null, 13);
		hm.put("张三",null);
		System.out.println(hm);//输出结果为:{null=13, 张三=null}。键或值为null,不会报错。
		
		Hashtable<String,Integer> ht = new Hashtable<>(); 
		/*
		ht.put(null, 13);
		System.out.println(ht);//如果键为null,系统报错:NullPointerException(空指针异常)。
		*/
		ht.put("李四",null);
		System.out.println(ht);////如果值为null,系统报错:NullPointerException(空指针异常)。
		System.out.println("11111111111111111111111");//出现异常的地方,后面的代码都不能执行,所以没有输出这句语句。
		//对比一下:HashMap 是 HashTable 的 升级版改良版,与 ArrayList(线程不安全) 是 vector(线程安全) 升级版改良版一样。
	}
}

线程安不安全的意思:

猜你喜欢

转载自blog.csdn.net/Ameir_yang/article/details/81460793
今日推荐