JAVA, in treemap want to change value, in object?

So, I declared Object class as TreeMap values.

public class Info {
    String name;
    String pName;// 부서이름
    String psw;//관리자비번
    public Info(String name,String pName, String psw){
       this.name = name;
       this.pName=pName;
       this.psw=psw;
    }

    public Info(String name,String psw){
       this.psw=psw;
    }

    public Info(String name){
        this.name=name;
    }
}


public class menu {
    Scanner sc = new Scanner(System.in);
    static TreeMap<String, Info> map = new TreeMap<String, Info>();
    public menu() {// constructor
        map.put("admin", new Info("admin","1234"));// initialize root 
    }
    private void adminChangePsw() {
        System.out.print("new password :");
        String data = sc.next();
        map.replace(admin, <value>);// howww?
    }

I want to change admin password, I tried to add the below code under class Info,

public Info(String psw){
    this.psw=psw;
}

but this code also has String type, so guess i can't use it

    public Info(String name){
        this.name=name;
    }

After few more attempts, found that replace(K,V) is what I need right now, but I don't know how to do if value is Object Class.

public void setPsw(String data){
    psw=data;
}

map.replace("admin",map.get("admin").setPsw(data));

I tried this also(lol), of course it did not work..

Anyone give me hint please, thanks :>

Upvotes: 1

Views: 2294

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

Any collection only contains references to objects. Not the objects itself. When you add a value/elment all you are doing is adding a reference to that object to the collection.

This means when you update a mutable object you don't need to place it back into the collection.

map.get("admin").setPsw(data);

This gets the reference to the Info and calls setPsw on it.

Note: if you have an immutable value and you get a new value, you have to replace it.

e.g. say you have

Map<String, Integer> map = ....
map.put("admin", map.get("admin") + 1); // the + 1 creates a new Integer reference.

BTW In Java 8 you can do

map.compute("admin", (k, v) -> v == null ? 1 : v + 1);

Upvotes: 7

Related Questions