java中Properties类

Properties是HashTable的子类,

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串
文档说明:
因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 putputAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 storesave 方法,则该调用将失败。类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNameslist 方法,则该调用将失败

例子:
public class PropertiesDemo {
public static void main(String[] args) {
Properties properties = new Properties();
//存
properties.setProperty("name", "zhangsan");
properties.setProperty("age", "27");
properties.setProperty("sex", "nan");
//取
String name = properties.getProperty("name");
String age = properties.getProperty("age");
String sex = properties.getProperty("sex");

System.out.println("name="+name);
System.out.println("age="+age);
System.out.println("sex="+sex);

//修改--就是key相同 value覆盖
properties.setProperty("age", "45");
}
}

Properties类的setProperty(String key, String value) 方法其实是调用 Hashtable 的方法 put。源码如下:

public synchronized Object setProperty(String key, String value) {
        return put(key, value);
    }

然后看 put(key, value);方法
    public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }


        // Makes sure the key is not already in the hashtable.
        Entry tab[] = table;
        int hash = hash(key);
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                V old = e.value;
                e.value = value;
                return old;
            }
        }


        modCount++;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();


            tab = table;
            hash = hash(key);
            index = (hash & 0x7FFFFFFF) % tab.length;
        }


        // Creates the new entry.
        Entry<K,V> e = tab[index];
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
        return null;
    }
这就是调用Hashtable的put方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值