Java Properties的坑

在Java中使用Properties对象时,尝试通过put()方法更新属性可能会失败。原因是Properties内部使用HashTable,当键已存在时,put()不会覆盖值。为安全地更新属性,应使用replace()方法。
摘要由CSDN通过智能技术生成

场景:

        在代码中使用了Properties,由于想要更新Properties中的属性,使用了put()方法,如下

Properties properties = new Properties();
properties.put("a","a");
properties.put("a","b");

        这时候再从properties中取值的时候,即

properties.get("a");

        惊奇的发现得到的是"a"而不是"b"。

        这是为什么呢?

        Properties底层使用的是HashTable,查看put的源代码

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 = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

        原来这里加了key是否存在的检测,如果key存在的话会直接返回,所以通过put()的方式来覆盖是不安全的

        如果想要覆盖,应该使用的是replace()方法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值