Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Difference between new Properties(...) and new Properties().putAll(...)

What's the difference between

    final Properties properties = new Properties(System.getProperties());

and

    final Properties properties = new Properties();
    properties.putAll(System.getProperties());

I've seen this change as a fix commit in JBoss AS.

like image 623
Ondra Žižka Avatar asked Mar 04 '12 16:03

Ondra Žižka


2 Answers

Here's an example which demonstrates the difference:

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"));
    }
}

In the first case, we're adding a new non-default value for the "x" property and then removing it; when we ask for "x" the implementation will spot that it's not present, and consult the defaults instead.

In the second case, we're copying the defaults into the property with no indication that they are defaults - they're just values for properties. We're then replacing the value for "x", then removing it. When as ask for "x" the implementation will spot that it's not present, but it doesn't have any default to consult, so the return value is null.

like image 71
Jon Skeet Avatar answered Nov 15 '22 02:11

Jon Skeet


The first sets the given properties as defaults; the second sets them as non-default values.

like image 26
jacobm Avatar answered Nov 15 '22 04:11

jacobm