[英]Get value from Map field of List element
I want to draw a String value from otherclass2
. 我想从
otherclass2
绘制一个String值。 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()
? 我应该使用
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. 您无法获取
otherclass2
的值,因为您的列表包含otherclass
实例,并且otherclass
具有private maps
=>,因此从list.get(0)
您无法访问maps
=>无法访问maps
也意味着您无法访问otherclass2
值。
Second problem is that you have not init otherclass2
and put it into maps
. 第二个问题是您没有初始化
otherclass2
并将其放入maps
。
To solve you problem (you should create get/setter instead of use public like here): 为了解决您的问题(您应该创建get / setter而不是像此处那样使用public):
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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.