Antifa
Antifa

Reputation: 387

Delete in array Java

I have that function where i want the user to pick a number of all schedules to delete one. My logic for delete is to find the i that I want to delete and then swap the last one schedule of my array with the i one, and then the last one to be null.

When i test my program i see that when I want to delete the last one of my array everything works ok, but when i try to delete something else an error shows up in eclipse.

Exception in thread "main" java.lang.NullPointerException I cant figure out what's happening. I have reviewed my code a lot of times.

 public void ScheduleDelete(){
    StandardInputRead readDeleteSchedule = new StandardInputRead();

    int deleteScheduleNum =readDeleteSchedule.readPositiveInt("Enter the schedule number you want to delete: ");
    for(int i=0;i<scheduleSize;i++){
        if(deleteScheduleNum==this.scheduleList[i].getScheduleNum()){
            this.scheduleList[i]= this.scheduleList[this.scheduleSize-1];
            this.scheduleList[i].setScheduleNum(i);
            this.scheduleList[this.scheduleSize-1]= null;
        }
    }
    this.scheduleSize--;
}

Upvotes: 0

Views: 794

Answers (1)

Attila
Attila

Reputation: 28812

When you swap the element with the last one the second time, you will replace the element with null (as you have just set the last element of the array to null in the previous swap). So when you want to use the element, you are operating on a null reference, hence the exception.

You need to keep track of how many active element you have in the array and swap the element with the last active one.

Alternatively, you can use a dynamic collection (e.g. a list) where you don't need to excplicitly keep track of the active elements because you only store the active ones.

Upvotes: 1

Related Questions