Java HashMap&Hashtable

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45778981/article/details/102765633

Java HashMap&Hashtable

HashMap与Hashtable的区别
(1)版本不同HashMap JDK 1.2 Hashtable 1.0
(2)Hashmap继承AbstractMap,实现了Map接口,Hashtabe继承Dictionary实现Map接口
(3)Hashmap允许null值和null键,但是null作为key只允一个,Hashtable非null键和值
(4)HashMap是线程不同步的(效率高,安全性低),Hashtable(效率低,安全性高)线程同步

1.HashMap

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

public class testHashMap {
	public static void main(String[] args) {
		//Map接口的特点,key不允许重复,值可以,且key是无序的
		//创建集合对象
		HashMap hm=new HashMap();
		//(1)添加元素
		hm.put("hello",123);//123自动装箱,Integer类型
		hm.put("world",456);
		hm.put("java",1000);
		hm.put("world",1000);//集合中的key可以重复,进行值的覆盖
		System.out.println("集合中的元素个数"+hm.size());
		System.out.println("集合是否为空"+hm.isEmpty());
		System.out.println(hm);
		System.out.println(hm.remove("world"));
		System.out.println(hm);
		//判断
		System.out.println(hm.containsKey("java")+"\t" +hm.containsKey("hhh"));
		System.out.println(hm.containsValue(1000));
		//获取所有key的集合
		Set set=hm.keySet();
		for(Object obj:set) {
			System.out.println(obj);
		}
		//获取所有value集合
		Collection coll=hm.values();	
		for(Object obj:coll) {
			System.out.println(obj);
		}
		//获取所有key-value集合
		Set entrySet=hm.entrySet();
		for(Object obj:entrySet) {
			System.out.println("obj");
		}	
	}
}

2.Hashtable

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

public class testHashtable {
	public static void main(String[] args) {
		//创建集合对象
		Hashtable ht=new Hashtable();
//		ht.put(null,null);
		System.out.println(ht);//NullPointerException
		HashMap hm=new HashMap();
		
		hm.put(null,null);
		hm.put(null,"hello");
		System.out.println(hm);	
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45778981/article/details/102765633