nishoof / elevator

It's an elevator
1 stars 0 forks source link

OutOfBoundsException when drawing queue #19

Open nishoof opened 3 hours ago

nishoof commented 3 hours ago

This is hard to reproduce.

Basically, when drawing the queue in the draw() method of Game, we very rarely get an ArrayIndexOutOfBoundsException in this:

int numPeopleInLine = peopleInLine.size();
int numPeopleToDisplay = Math.min(numPeopleInLine, MAX_QUEUE_DISPLAYED);
int numPeopleNotDisplayed = numPeopleInLine - numPeopleToDisplay;
for (int i = 0; i < numPeopleToDisplay; i++) {
    peopleInLine.get(i).draw(d, 20, 130 + i * 24);
}
nishoof commented 3 hours ago

Pretty sure this is happening because we remove people in the Elevator reachedFloor() method:

// Bring people into the elevator
int n2 = 0;      // number of people removed from the line
ArrayList<Person> peopleInLine = game.getPeopleInLine();
for (int i = 0; i < peopleInLine.size() + n2; i++) {
    if (peopleInElevator.size() == elevatorCapacity) {
        System.out.println("Elevator is full");
        break;
    }
    Person person = peopleInLine.get(i - n2);
    if (person.getCurrentFloor() != this.getCurrentFloor()) continue;
    n2++;
    person.cancelTimer();
    peopleInLine.remove(person);
    peopleInElevator.add(person);
    System.out.println("Person from floor " + person.getCurrentFloor() + " added to elevator");
}

This code sometimes runs at the same time as the queue is being drawn. Basically, we're modifying the queue while iterating through it at the same time.

Might be able to fix this by adding the task to remove a Person to a queue kind of thing, so we modify the ArrayList in the draw() method.

nishoof commented 3 hours ago

Or it might be better to just make a copy of the ArrayList when drawing it. Or even just catching the exception could work.