[英]Java NullPointerException In the constructor's class
I have made a Java class where I have defined a constructor and some methods but I get a NullPointer Exception, and I don't know how I could fix It. 我做了一个Java类,其中定义了一个构造函数和一些方法,但是却收到NullPointer异常,而且我不知道如何解决它。
public class Job {
String idJob;
int time;
int timeRun;
Job j1;
List<Job> startBeforeStart;
List<Job> restricted;
Job(String idJob, int time){
this.idJob=idJob;
this.time=time;
}
public boolean isRestricted() {
return restricted.size() != 0;
}
public void startsBeforeStartOf(Job job){
startBeforeStart.add(job);
job.restricted.add(this);
}
public void startsAfterStartOf(Job job){
job.startsBeforeStartOf(this);
}
public void checkRestrictions(){
if (!isRestricted()){
System.out.println("+\n");
}
else{
Iterator<Job> itR = restricted.iterator();
while(itR.hasNext()){
Job j1 = itR.next();
if(time>timeRun){
System.out.println("-\n");
time--;
}
else {
restricted.remove(j1);
}
}
}
}
@Override
public boolean equals(Object obj) {
return obj instanceof Job && ((Job) obj).idJob.equals(idJob);
}
public void run() {
timeRun++;
}
}
PS Looking in a forum a user says that to fix the error I should make an ArrayList inside the constructor (without modify the received parameters that should remain String id and int time ), but I haven't understand what He mean. PS在论坛上看到一个用户说,要解决该错误,我应该在构造函数内创建一个ArrayList(而不修改接收的参数,这些参数应保持String id和int time ),但我不明白他的意思。
You are not creating an instrance of List<Job>
for both the lists startBeforeStart
and restricted
- you only declare a variable, which is assigned with a null pointer. 您不会同时为列表
startBeforeStart
和restricted
List<Job>
创建List<Job>
的startBeforeStart
-您仅声明一个变量,该变量分配startBeforeStart
指针。
Thus, whenever you try to access this List
[for example: return restricted.size() != 0;
因此,每当您尝试访问此
List
[例如: return restricted.size() != 0;
] - you are trying to dereference a null pointer - which causes your NPE. ]-您正试图取消引用空指针-这会导致您的NPE。
You should create an instance of the List
- using the new
operator [probably in the constructor]. 您应该使用
new
运算符[可能在构造函数中]创建List
的实例。
Have a look at ArrayList
and LinkedList
and chose which is better for you. 看一下
ArrayList
和LinkedList
然后选择哪个更适合您。
For example, if you use to use an ArrayList
for both, your c'tor should be something like: 例如,如果您过去都使用
ArrayList
,则您的c'tor应该类似于:
Job(String idJob, int time){
this.idJob=idJob;
this.time=time;
startBeforeStart = new ArrayList<Job>();
restricted= new ArrayList<Job>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.