这是我的主要代码:

package onlineTest;

import java.util.HashSet;
import java.util.Iterator;

public class TestClass {

  public static void main(String[] args) {
    HashSet<TrueFalseQuestion> newList = new  HashSet<TrueFalseQuestion>();
    newList.add(new TrueFalseQuestion(1, 2, "sms", 4, true));
    newList.add(new TrueFalseQuestion(2, 3, "erw", 5, false));
    newList.add(new TrueFalseQuestion(3, 4, "Gray", 6, true));

    Iterator<TrueFalseQuestion> iterator = newList.iterator();
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
      System.out.println(iterator.next().getPoints());
    }
  }
}


这是我的TrueFalseQuestion类:

public class TrueFalseQuestion {

  public int examId;
  public int questionNum;
  public String text;
  public double points;
  public boolean answer;

  public TrueFalseQuestion(int examId, int questionNum, String text,
        double points, boolean answer) {
    this.examId = examId;
    this.questionNum = questionNum;
    this.text = text;
    this.points = points;
    this.answer = answer;
  }

  public int getExamId() {
    return examId;
  }

  public int getQuestionNum() {
    return questionNum;
  }

  public String getQuestionText() {
    return text;
  }

  public boolean getAnswer() {
    return answer;
  }

  public double getPoints() {
    return points;
  }
}


当我运行我的代码时,它可以进行第一次迭代并很好地打印出要点,但随后在第二次迭代中给出一个NullPointerException。出现错误的行是:

System.out.println(iterator.next().getPoints());


我不知道是什么问题。我假设iterator.next()是当前的TrueFalseQuestion对象,并且每次迭代都可以使用getPoints()

最佳答案

这是因为您在每个itertor.next()的循环中两次调用iterator.hasNext()

你应该做:

while(iterator.hasNext()) {
  TrueFalseQuestion trueFalseQuestion = iterator.next();
  System.out.println(trueFalseQuestion);
  System.out.println(trueFalseQuestion.getPoints());
}


在第一次迭代中发生的是,当您调用时:

System.out.println(iterator.next());


当您执行以下操作时,第一个TrueFalseQuestion将被打印,但是在下一个语句中:

System.out.println(iterator.next().getPoints());


您在不知不觉中打印第二个pointsTrueFalseQuestion

因此,在您进行第二次迭代时,再次执行以下操作:

System.out.println(iterator.next());


在执行此操作时,将在下一行最后打印第三个TrueFalseQuestion

System.out.println(iterator.next().getPoints());


没有第四个TrueFalseQuestion,您会得到一个NullPointerException,因为您要在getPoints()值上调用null

07-24 08:48