使用 applicationContext.xml 中的答案 Bean 填充问题 Bean 使用迭代器迭代答案列表时会引发错误,但使用 For Each 循环可以正常工作。
{
<bean id="answer1" class="com.core.spring.Answer">
<property name="id" value="1"></property>
<property name="answerText" value="Java is a programming language"></property>
<property name="by" value="Ravi Malik"></property>
</bean>
<bean id="answer2" class="com.core.spring.Answer">
<property name="id" value="2"></property>
<property name="answerText" value="Java is a platform"></property>
<property name="by" value="Sachin"></property>
</bean>
<bean id="answer3" class="com.core.spring.Answer">
<property name="id" value="3"></property>
<property name="answerText" value="Java is a platform"></property>
<property name="by" value="Sachin"></property>
</bean>
<bean id="question" class="com.core.spring.Question">
<property name="id" value="1"></property>
<property name="questionText" value="What is Java?"></property>
<property name="answers">
<list>
<ref bean="answer1"/>
<ref bean="answer2"/>
<ref bean="answer3"/>
</list>
</property>
</bean>
}
这是问题的 Bean 类。
{
package com.core.spring;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
String questionText;
List<Answer> answers=new ArrayList<Answer>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
public void displayInfo(){
System.out.println("Question: "+id);
System.out.println(questionText);
System.out.println("Answers");
for(Answer ans:answers){
System.out.print(ans.getId());
System.out.println(": "+ans.getAnswerText());
}
for (Iterator<Answer> ans = answers.iterator(); ans.hasNext();){
System.out.print(ans.next().getId());
System.out.println(": "+ans.next().getAnswerText());
}
/*Iterator<Answer> ans=answers.iterator();
while(ans.hasNext()){
System.out.print(ans.next().getId());
System.out.println(": "+ans.next().getAnswerText());
}*/
}
}**
}
最佳答案
您对 Iterator
的使用是错误的 - next()
将迭代器移动到下一个位置,而您两次调用它来自 while
循环体,并且仅检查 hasNext()
一次。
您应该只调用 next()
一次,将其值提取到局部变量并根据需要使用它多次:
Iterator<Answer> ans = answers.iterator();
while(ans.hasNext()) {
Answer answer = ans.next();
System.out.print(answer.getId());
System.out.println(": " + answer.getAnswerText());
}
关于java - 无法使用 Iterator 迭代 List,但在使用 for every 时工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20921788/