Java 集合框架(Map实现类Hashtable, Properties)

本文详细介绍了哈希表(HashTable)的特性,包括其键值对存储、不允许键值为null、线程安全及扩容机制。当元素数量达到容量的75%时,哈希表会进行扩容,扩容规则为当前容量的2倍加1。Properties类作为HashTable的子类,用于处理.properties配置文件,遵循相同的安全特性,并提供了加载、修改和删除配置的API。
摘要由CSDN通过智能技术生成

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");//查

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Meikesibondwell

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值