Java: the 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 saw this change as commit commit in JBoss AS .

+4
source share
2 answers

Here is an example showing 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 add a new value that is different from the default value for the "x" property, and then delete it; when we request "x", the implementation will see that it is missing, and consult the default settings instead.

In the second case, we copy the default values ​​to the property without indicating that they are by default - they are simply property values. Then we replace the value "x" and then delete it. When the implementation as the request "x" sees that it is not present, but it has no default recommendations, therefore the return value is null.

+6
source

The first sets the default properties specified; the second sets them as values ​​other than the default values.

+2
source

Source: https://habr.com/ru/post/1399669/


All Articles