Search code examples
javaarraylistinterfacefactory-pattern

Factory Pattern/ArrayList/Interface Issue


I am using a factory pattern to create different types of elevators using the ElevatorMover interface. The factory is store the elevators in an ArrayList of ElevatorMover objects. When I retrieve an elevator [ElevatorArrayList.get(i)] from the ArrayList, I am unable to call PassengerElevator methods. Only ElevatorMover methods (which are not implemented of course).

What am I failing to do here?

Here is the code I'm trying to call in main

// make elevator 1 go to the 11th floor
testBuilding.getElevator(1).moveUp(11);

This is my interface

public interface ElevatorMover {

public void moveUp(int i);

public void moveDown(int i);

public void openDoors();

This is the PassengerElevator method

@Override
public void moveUp(int i) {
    while (currentFloor != i) {
        setCurrentFloor(currentFloor++);
    }
}

The error message

Exception in thread "main" java.lang.NullPointerException
    at Elevator.Building.getElevator(Building.java:109)
    at Elevator.ElevatorSimulatorMain.main(ElevatorSimulatorMain.java:34)

Building.class constructor

private ArrayList<Floor> floorArrayList; // the ArrayList of floors in the building
private ArrayList<ElevatorMover> elevatorArrayList; // the ArrayList of elevators in the building

public Building(int numFloors, int numElevators) {

    this.numFloors = numFloors;
    this.numElevators = numElevators;

    // create each floor
    if (numFloors > 0) // Must have 1 or more floors
    {
        for (int i = 1; i <= numFloors; i++) {
            floorArrayList.add(new Floor(i));
        }
    }
    else 
    {
        System.out.println("Building must have 1 or more floors.");
    }

    // create each elevator.
    if (numElevators > 0) //  Must have 1 or more elevators
    {
        for (int i = 1; i <= numElevators; i++) {
        elevatorArrayList.add(ElevatorFactory.build("Passenger", i));
        }
    }
    else
    {
        System.out.println("Building must have 1 or more elevators.");
    }
}

ElevatorFactory build method

public static ElevatorMover build(String type, int elevID) {

    if (type.equals("Passenger")) {
        return new PassengerElevator(elevID);
    }
    else return null; // don't know what this is
}

The getElevator method

public ElevatorMover getElevator(int i) {
    return elevatorArrayList.get(i);
}

Solution

  • I am guessing you did not create elevatorArrayList. Example

    List<ElevatorMover> elevatorArrayList = new ArrayList<ElevatorMover>();

    private ArrayList<ElevatorMover> elevatorArrayList; // This is just declaring not creating elevatorArrayList