Reputation: 645
import java.util.Map;
class Test {
public static void main(String[] args) {
Map<String, String> env = System.getenv();
System.out.println(env);
env.put("ID", "1");
}
}
I am adding some key value pairs in the map while initializing and then again adding one key value pair so what is wrong with the program?
Upvotes: 3
Views: 1128
Reputation: 11642
I am adding some key value pairs in the map while initializing
No, you're not. You're initializing a Map reference variable, env
, to refer to a pre-existing map that is returned by the call to System.getEnv()
.
and then again adding one key value pair so what is wrong with the program?
As said above, you're trying to add a key-value pair for the first time. The the Javadoc for Map. It says the put
method is an optional operation. And, indeed, the type of map that getEnv()
returns doesn't support put()
.
What exactly are you trying to do? If you want to change the environment for a subprocess, use the ProcessBuilder
class, which allows you to specify additional environment variables. If you are trying to change the environment for the current process, then just create your own private Map, copy into it all entries from getEnv()
, and then use your own map instead of getEnv()
wherever you need to.
Upvotes: 0
Reputation: 122006
No you cannot modify the returned map.
System#getEnv() returns unmodifiable map
Returns an unmodifiable string map view of the current system environment.
The reason being is that the map contains info about system that being run and you cannot simply add info programatically.
Upvotes: 3