JAVA HashTable和Properties

HashTable

一、HashTable的基本介绍

  1. 存放的元素是键值对:即K-V
  2. hashTable的键和值都不能为null,否则会抛出NullPointerException
  3. hashTable使用方法基本上和HashMap一样
  4. hashTable线程安全的,hashMap线程不安全
  5. 简单看下底层结构

  • 在底层是一个数组
    • Hashtable$Entry[] 初始化大小为 11
  • 临界值:threshold 8 = 11 * 0.75
  • 扩容:按照自己的扩容机制来扩容即可
  • 执行 方法addEntry(hash, key, value, index);,添加K-V封装到Entry里面去
  • 按照int newCapacity = (oldCapacity << 1) + 1;进行扩容
    • 即扩容原来数组的两倍 还要+1

二、HashTable和HashMap对比

版本 线程安全(同步) 效率 允许null键null值
HashMap 1.2 不安全 可以
HashTable 1.0 安全 较低 不可以

三、Properties

  1. Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存数据
  2. 他的使用特点和Hashtable类似
  3. Properties还可以用于从 xxx.properties文件中,加载数据到Properties类对象,并进行读取和修改
  4. 说明:工作后xxx.properties文件通常作为配置文件,这个知识点在IO流举例
package com.hspedu.map_;

import java.util.Properties;

/**
 * @author DL5O
 * @version 1.0
 */
public class Properties_ {
    public static void main(String[] args) {
        //1. Properties 继承了 HashTable
        //2. 可以通过k-v来存放数据,当然key 和 value 不能为空
        //增加
        Properties properties = new Properties();
        properties.put("john",100);
//        properties.put(null,100);
//        NullPointerException 空指针异常,键是不能为空的

//        properties.put("john",null);
        //空指针异常,value值也不能为空
        properties.put("lucy",100);
        properties.put("lic",100);
        properties.put("lic",88);//如果有相同的key,那么值就会被替换
        System.out.println(properties);
        //{lic=88, john=100, lucy=100}

        //如何通过key获取对应的值
        System.out.println(properties.get("lic"));//88

        //删除元素
        properties.remove("lic");
        System.out.println(properties);//{john=100, lucy=100}

        //修改
        properties.put("john","约翰");
        System.out.println(properties);

        //查找
        System.out.println(properties.get("john"));//约翰
        System.out.println(properties.getProperty("john"));//约翰

    }
}

posted @ 2022-04-08 14:31  DL50  阅读(45)  评论(0编辑  收藏  举报