hashtable:
1.存放的是k-v键值对
2.hashtable的键和值都不能为null,否则会抛出NullPointerException
3.HashTable在使用方法上和HashMap基本一样
4.HashTable线程安全,HashMap线程不安全
5.底层是一个HashTable$Entry类型的数组
对于hashtable无参构造:初始化table容量为11,加载因子为0.75,即当数组内元素达到0.75 * Capacity 触发扩容。
public Hashtable() { this(11, 0.75f); }
扩容机制:
1.执行方法addEntry ,将k-v封装成一个Entry:
private void addEntry(int hash, K key, V value, int index) { modCount++; 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++; }
2.如果count 达到threshold(0.75倍的容量)调用rehash(): 扩容规则为newCapacity = (oldCapacity << 1) + 1【即2x + 1】
protected void rehash() { int oldCapacity = table.length; Entry<?,?>[] oldMap = table; // overflow-conscious code int newCapacity = (oldCapacity << 1) + 1;//扩容规则
Properties:继承自HashTable类并且实现了Map接口,也是用键值对形式保存数据
使用特点和HashTable类似
用途:从XXX.properties文件中加载数据到properties类对象,并进行读取和修改,因此properties常用于作配置文件
常用方法:
Properties properties = new Properties(); //properties.put(null, "abc");//抛出 空指针异常 //properties.put("abc", null); //抛出 空指针异常 properties.put("john", 100);//k-v properties.put("lic", 100); properties.put("lic", 88);//如果有相同的 key , value 被替换 System.out.println(properties.get("lic"));//通过键获取. properties.remove("lic");//删除 properties.put("john", "约翰");//修改 //properties.setproperties("john", "aa");//改 //properties.getproperties("john");//查