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.
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.
You are not creating an instrance of
List<Job>for both the listsstartBeforeStartandrestricted– you only declare a variable, which is assigned with a null pointer.Thus, whenever you try to access this
List[for example:return restricted.size() != 0;] – you are trying to dereference a null pointer – which causes your NPE.You should create an instance of the
List– using thenewoperator [probably in the constructor].Have a look at
ArrayListandLinkedListand chose which is better for you.For example, if you use to use an
ArrayListfor both, your c’tor should be something like: