【Java】Hashtable讲解
Hashtable是一个散列表,存储的内容是键值对映射。
Hashtable继承Directory,实现了Map接口。
Hashtable是线程安全的哈希表实现。
通常情况下,默认负载因子是0.75,这是在时间和空间成本上寻求的一种折中。负载因子过高虽然减少了空间的开销,但是同时也增加了查找某个条码的时间。
基础操作
创建实例
Hashtable默认构造器的初始容量是11,负载因子0.75。可以在构造实例时指定初始容量和负载因子,如初始容量设置为0,会被自动修正为1。
扩容:当元素数量超过容量*负载因子时自动扩容,每次扩容为原容量的2倍。
import java.util.Hashtable;
// 默认构造
Hashtable<Integer, Integer> hashtable1 = new Hashtable();
// 指定容量和负载因子
Hashtable<Integer, Integer> hashtable2 = new Hashtable(20, 0.8f);
添加/修改元素
使用put(key, value)方法,键值均不可为null。
Hashtable<String, Integer> hashtable = new Hashtable();
// 添加元素
hashtable.put("Apple", 1);
System.out.println(hashtable); // {Apple=1}
// 修改元素
hashtable.put("Apple", 3);
System.out.println(hashtable); // {Apple=3}
获取元素
通过get(key)根据键查找值,若键不存在返回null。
Integer value = hashtable.get("Apple");
System.out.println(value); // 3
删除元素
使用remove(key)删除指定键的键值对。
hashtable.remove("Apple");
System.out.println(hashtable); // {}
获取键值对数量
使用size()获取键值对的数量。
hashtable.put("Apple", 1);
hashtable.put("Orange", 2);
hashtable.put("Banana", 3);
System.out.println(hashtable.size()); // 3
清空Hashtable
使用clear()清空Hashtable
hashtable.clear();
System.out.println(hashtable); // {}
其他常用方法
键集合
通过keySet()获取所有键。
Hashtable<String, Integer> hashtable = new Hashtable();
hashtable.put("Apple", 1);
hashtable.put("Orange", 2);
hashtable.put("Banana", 3);
System.out.println(hashtable.keySet()); // [Orange, Apple, Banana]
键值对集合
使用entrySet()获取Entry对象集合。
Hashtable<String, Integer> hashtable = new Hashtable();
hashtable.put("Apple", 1);
hashtable.put("Orange", 2);
hashtable.put("Banana", 3);
System.out.println(hashtable.entrySet()); // [Orange=2, Apple=1, Banana=3]
检查键/值是否存在
通过containsKey(key)检查键是否存在。
通过containsValue(value)/contains(value)检查值是否存在。
Hashtable<String, Integer> hashtable = new Hashtable();
hashtable.put("Apple", 1);
hashtable.put("Orange", 2);
hashtable.put("Banana", 3);
System.out.println(hashtable.containsKey("Apple")); // true
System.out.println(hashtable.containsValue(5)); // false
System.out.println(hashtable.contains(3)); // true
浙公网安备 33010602011771号