场景:
在代码中使用了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()方法