- Properties基本介绍
- Properties用法
- Properties源码剖析
Properties可以用于从*.properties中加载数据到Properties类对象,进行数据的读取和修改。
工作中*.properties通常作为配置文件。
Properties用法public class Properties_ {
public static void main(String[] args) {
Properties properties = new Properties();
//1.put
//不能存null key或者null value。 public class Properties extends Hashtable
=====put=====
{1003=ada, 1002=cara, 1001=lucky}
=====get=====
lucky
=====getProperty(String key)=====
cara
=====getProperty(String key, String defaultValue)=====
user not exists
=====remove=====
{1002=cara, 1001=lucky}
Properties源码剖析
public Properties() {
this(null);
}
public Properties(Properties defaults) {
this.defaults = defaults;
}
public Hashtable() {
this(11, 0.75f);
}
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 entry = (Entry)tab[index];
for(; entry != null ; entry = entry.next) {
//如果要插入的的key的hash值和准备插入的table索引位置的对象的hash值一样,并且equals方法相等,那么就执行替换操作
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;//替换
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
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
//如果table中的数据大于等于临界值,就会扩容
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry e = (Entry) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
protected void rehash() {
int oldCapacity = table.length;
Entry,?>[] oldMap = table;
// overflow-conscious code
//2*oldCapacity + 1
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry,?>[] newMap = new Entry,?>[newCapacity];
modCount++;
//计算新的临界值
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
//遍历旧数据,将原来的值再放到新的map上
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry old = (Entry)oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry)newMap[index];
newMap[index] = e;
}
}
}



