当我在第二个for循环中使用subject.getSubjectHasProgram()获得设置接口(interface)时,得到NullPointerException。但是subject.getSubjectHasProgram()。size()显示等于2,这是我想要的.. !!

   Set<Subject> sub=(Set<Subject>)this.teacher.getSubjects();
   for (Iterator<Subject> iterator = sub.iterator(); iterator.hasNext();) {
       Subject next = (Subject)iterator.next();
       if(next.getID()==this.ID){
           this.Name=next.getName();
           System.out.println("Subject Name="+this.Name);
           this.CourseCode=next.getCourseCode();
           this.CreditHour=next.getCreditHour();
           **System.out.println("programscount="+next.getSubjectHasPrograms().size());**
            for (Iterator iterator2 = next.getSubjectHasPrograms().iterator(); iterator2.hasNext();){
                ProgramHasSubject programHasSubject = (ProgramHasSubject) iterator2.next();
                this.selectedPrograms.add(programHasSubject.getProgram_ID());
                System.out.println("Program ID : " + programHasSubject.getProgram_ID().getID());
                System.out.println("Program Name : " + programHasSubject.getProgram_ID().getName());
                System.out.println("Semester : " + programHasSubject.getSemester_ID());
            }
           break;
       }

   }

最佳答案

在for循环中,您实际上有两个语句。

Iterator iterator2 = next.getSubjectHasPrograms().iterator();
and
iterator2.hasNext();

您是否已验证next.getSubjectHasPrograms().iterator();不返回null

08-03 12:43