简体   繁体   中英

Get value from Map field of List element

I want to draw a String value from otherclass2 . How can I do this?

public class Main {
    public static void main(String[] args) {
        List<otherclass> list = new ArrayList<otherclass>();

        list.add(new otherclass());
    }
}


public class otherclass {
    private Map<String, otherclass2> maps = new HashMap<String, otherclass2>();
}

public class otherclass2 {
    String value = "I want this String";
}

Should I use list.get() ? Or is there another approach?

You can not get the value of otherclass2 because your list contain instance of otherclass and the otherclass is have a private maps => so that from the list.get(0) you can not access the maps => can not access maps also mean you can not access otherclass2 value.

Second problem is that you have not init otherclass2 and put it into maps .

To solve you problem (you should create get/setter instead of use public like here):

public class Main {
    public static void main(String[] args){
        List<otherclass> list = new ArrayList<otherclass>();
        list.add(new otherclass());
        otherclass other = list.get(0);
        String your_value = other.maps.get("first").value;
        System.out.println(your_value);
    }
}

public class otherclass{
    public Map<String, otherclass2> maps = new HashMap<String, otherclass2>();
    public otherclass(){
        maps.put("first", new otherclass2());
    }
}

public class otherclass2{
    public String value = "I want this String"
}

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