集合源码分析08——Map——Properties分析

Properties分析

  • 案例引入

  

  • 传统方法:

这时如果我们要求只获取一个值就比较麻烦

  • 基本介绍

Java 读写Properties配置文件 - 旭东的博客 - 博客园 (cnblogs.com)

 

   1.可以看到Properties是Hashtable的子类所以也间接实现了Map接口

          

  2.因为是Hashtable的子类所以K、V值也都不能为空

 

 

  3.

package collection.map;

import java.util.Properties;

public class Properties01 {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("name","root");
        properties.put("password","123456");
        System.out.println(properties);
        System.out.println(properties.get("name"));
    }
}

 

  •  常用方法:

 http://tool.chinaz.com/tools/unicode.aspx

代码演示:

1.读取

 

 

 

 2.写入

 

 

 这里第二个参数是注解,如果没有要求可以置空

3.修改

 

 put方法源码:

public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException(); 可以看到V不能为空
        }

        // 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;  如果key存在就替换
                return old;
            }
        }

        addEntry(hash, key, value, index); 如果是新的key就添加
        return null;
    }

 

  • 创建properties文件

 

 

 

 

 

 

 

 

  

 

posted @ 2022-01-21 15:23  紫英626  阅读(33)  评论(0编辑  收藏  举报

紫英