1.基本介绍
HashTable
的键和值都不能为空,否则会抛出一个异常
使用方法基本与HashMap
一致
HashTable
是线程安全的HashMap
是不线程安全的
2.HashTable底层
先上代码:
Hashtable hashtable = new Hashtable(); hashtable.put("john",100); hashtable.put("tom",250); hashtable.put("tom",1314); System.out.println(hashtable); // {tom=1314, john=100}
是否为空,如果为空直接抛出一个异常value
方法最前面先判断了put
方法,可以看到在put
先进入
if (value == null) { throw new NullPointerException(); }
也存在替换机制和扩容机制!🎈HashTable
同样的,
3.HashTable扩容机制
HashMap
和HashSet
拥有自己的扩容机制,这不同于HashTable
添加键值对时,真正起到添加作用的是如下方法:HashTable
首先,我们要明白,在
addEntry(hash, key, value, index);
我们来看一下他的真面目:
private void addEntry(int hash, K key, V value, int index) { Entry<?,?> tab[] = table; if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; hash = key.hashCode(); index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) tab[index]; tab[index] = new Entry<>(hash, key, value, e); count++; modCount++; }
继续追进去到rehash
方法:
private void addEntry(int hash, K key, V value, int index) { Entry<?,?> tab[] = table; if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; hash = key.hashCode(); index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>) tab[index]; tab[index] = new Entry<>(hash, key, value, e); count++; modCount++; }
当添加的元素数量大于临界值时,执行rehash
方法(这个方法就是真正的扩容方法)
if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; hash = key.hashCode(); index = (hash & 0x7FFFFFFF) % tab.length; }
首先,拿到老的容量:
int oldCapacity = table.length;
新的容量为老的容量 * 2 + 1
:
int newCapacity = (oldCapacity << 1) + 1;
继续往下,到达真正扩容的代码:
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity]
4.HashMap和HashTable的对比
5.Properties
Properties继承了HashTable
一般用于可操作的配置文件编写
使用实例:
import java.util.Properties; /** * Properties演示 */ public class PropertiesText { @SuppressWarnings({"all"}) public static void main(String[] args) { Properties properties = new Properties(); // 增加 properties.put("john",521); properties.put("tom",1314); properties.put("tom",100); System.out.println(properties); // {tom=100, john=521} // 通过key获取值 System.out.println(properties.get("tom")); // 100 // 删除 properties.remove("tom"); System.out.println(properties); // {john=521} } }
6.集合选型规则🙌
存储一组对象:Collection
允许重复,增删多选LinkedList,改查多选ArrayList
不允许重复,无序选HashSet,排序选TreeSet,插入和取出顺序一致选择LinkedHashSet
存储键值对:Map
键无序:HashMap
键排序:TreeMap
键插入和取出顺序一致:LinkedHashMap
读取文件:Properties