简体   繁体   中英

Why is this program throwing java.lang.UnsupportedOperationException

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM