基本介绍
1)Properties类继承自Hashtable类并实现了Map接口,也是使用键值对的形式保存数据;
2)使用特点与Hashtable类似;
3)Properties可以用于从xxx.properties文件中,加载数据到Properties类对象,并进行读取和修改;
4)xxx.properties文件通常作为配置文件,在IO流进行举例说明。
常用方法
package com.pero.map_;
import java.util.Properties;
/**
* Properties类
* @author Pero
* @version 1.0
*/
@SuppressWarnings({"all"})
public class Properties_ {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("jake",1);
properties.put("lucy",2);
//properties.put(null,3); //key不能为空,会抛出NullPointerException
//properties.put("tom",4); //value不能为空,会抛出NullPointerException
properties.put("smith",5);
properties.put("jake",9); //相同key,则进行替换,修改value的值
System.out.println(properties);
//如何通过key获取对应的value
//第一种,通过get(key)来获取value的值
System.out.println(properties.get("jake"));
//第二种,通过getProperty(key)来获取value的值
System.out.println(properties.getProperty("jake"));
//remove(key)方法或者remove(key,value),删除目标数据
System.out.println(properties.remove("lucy"));
//System.out.println(properties.remove("lucy",2));
//修改
properties.put("jake","杰克");
}
}
源码分析
1)执行构造器:
public Properties() {
this(null);
}
public Properties(Properties defaults) {
this.defaults = defaults;
}
/**
* A property list that contains default values for any keys not
* found in this property list.
*
* @serial
*/
protected Properties defaults;
2) 执行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;
}
集合选型规则
1)先判断存储类型(一组对象还是一组键值对)
2)一组对象【单列】:Collection接口
允许重复:List接口
增删多:LinkedList类【底层维护了一个双向链表】
改查多:ArrayList类【底层维护了Object类型的可变数组】
不允许重复:Set接口
无序:HashSet类【底层是HashMap,维护了hash表(数组+链表+红黑树)】
排序:TreeSet类
插入和去除顺序一致:LinkedHashSet类【底层维护了数组+双向链表】
3)一组键值对【双列】:Map接口
键无序:HashMap类【底层是:hash表;jdk7:数组+链表;jdk8:数组+链表+红黑树】
键排序:TreeMap类
键插入和去除顺序一致:LinkedHashMap类【底层是:数组+双链表链表】
读取文件:Properties类