我有一个叫做答案的对象。我可以用值填充对象,但我不知道如何获取它的列表。
public class Answer{
private HashMap<String, Integer> answer;
public Answer(HashMap<String, Integer> answer) {
this.answer = answer;
}
public HashMap<String, Integer> getAnswer() {
return answer;
}
}
final Answer answers = new Answer(new HashMap<String, Integer>() {{
put("STRING1",1);
put("STRING2",2);
put("STRING3",3);
}});
我试图为每个人使用,但这不正确。请指教,如何列出。谢谢。
for (Answer answer:answers) {
}
答案 0 :(得分:1)
班级答案:
import java.util.HashMap;
public class Answer{
private HashMap<String, Integer> answer;
public Answer(HashMap<String,Integer> hashMap) {
this.answer = hashMap;
}
public HashMap<String, Integer> getAnswer() {
return answer;
}
}
使用Class:
import java.util.HashMap;
public class main {
main(){
final Answer answers = new Answer(new HashMap<String,Integer>(){{
put("STRING1",1);
put("STRING2",2);
put("STRING3",3);
}});
for(HashMap.Entry<String, Integer> entry : answers.getAnswer().entrySet()){
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static void main(String[] args) {
new main();
}
}
生成输出:
STRING3: 3
STRING1: 1
STRING2: 2
Altough如果您的答案Class不会做任何其他事情,我强烈建议您使用Hashmap并将其命名为答案,因为目前您的答案类只存储没有任何好处的Hashmap