Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 迭代过程中出现HashSet NullPointerException错误_Java_Class_Nullpointerexception_Iterator_Hashset - Fatal编程技术网

Java 迭代过程中出现HashSet NullPointerException错误

Java 迭代过程中出现HashSet NullPointerException错误,java,class,nullpointerexception,iterator,hashset,Java,Class,Nullpointerexception,Iterator,Hashset,这是我的主要代码: 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>(); new

这是我的主要代码:

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());
    }
  }
}
当我运行代码时,它能够通过第一次迭代并很好地打印出这些点,但是在第二次迭代中它会给出一个
NullPointerException
。显示错误的行是:

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

我不知道是什么问题。我假设迭代器.next()是当前的
TrueFalseQuestion
对象,并且每次迭代,我都可以使用
getPoints()
,这是因为您在循环中为每个
迭代器调用
itertor.next()
两次

你应该做:

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());
System.out.println(iterator.next());
System.out.println(iterator.next().getPoints());
您正在不知不觉地打印第二个
TrueFalseQuestion

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

System.out.println(iterator.next().getPoints());
System.out.println(iterator.next());
System.out.println(iterator.next().getPoints());
第三个
TrueFalseQuestion
将被打印,最后,当您执行以下操作时,将打印在下一行:

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

没有第四个
TrueFalseQuestion
问题,您会得到一个
NullPointerException
,因为您正在对
null
值调用
getPoints()

程序中的数组值找不到数组,因此它会显示null指针异常
注意,数组索引以0开头

您确定它是从
System.out.println(iterator.next().getPoints())抛出的吗行?什么
System.out.println(iterator.next())打印?你确定你得到的是
NullPointerException
?不是
非接触式异常