📅  最后修改于: 2020-12-04 07:20:39             🧑  作者: Mango
在此示例中,我们使用地图作为具有已发布用户名答案的答案。在这里,我们将键和值对都用作字符串。
像前面的示例一样,它是论坛的示例,其中一个问题可以有多个答案。
此类包含三个属性,两个构造函数和用于显示信息的displayInfo()方法。
package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map answers;
public Question() {}
public Question(int id, String name, Map answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set> set=answers.entrySet();
Iterator> itr=set.iterator();
while(itr.hasNext()){
Entry entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
map的entry属性用于定义键和值信息。
此类从applicationContext.xml文件获取Bean,然后调用displayInfo()方法。
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}