Java:新属性(...)和新属性()之间的区别.putAll(...)

Ond*_*žka 4 java constructor properties map

有什么区别

    final Properties properties = new Properties(System.getProperties());
Run Code Online (Sandbox Code Playgroud)

    final Properties properties = new Properties();
    properties.putAll(System.getProperties());
Run Code Online (Sandbox Code Playgroud)

我已经看到这个变化是JBoss AS中修复提交.

Jon*_*eet 6

这是一个展示差异的例子:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Properties defaults = new Properties();
        defaults.setProperty("x", "x-default");

        Properties withDefaults = new Properties(defaults);
        withDefaults.setProperty("x", "x-new");
        withDefaults.remove("x");
        // Prints x-default
        System.out.println(withDefaults.getProperty("x"));

        Properties withCopy = new Properties();
        withCopy.putAll(defaults);
        withCopy.setProperty("x", "x-new");
        withCopy.remove("x");
        // Prints null
        System.out.println(withCopy.getProperty("x"));
    }
}
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,我们为"x"属性添加一个新的非默认值,然后将其删除; 当我们要求"x"时,实现会发现它不存在,并参考默认值.

在第二种情况下,我们将默认值复制到属性中,并没有表明它们默认值 - 它们只是属性的值.然后我们将"x"的值替换掉,然后将其删除.当请求"x"时,实现将发现它不存在,但它没有任何默认值,因此返回值为null.