Sohail
Sohail

Reputation: 1147

java object arraylist index

I am running following code in java and have some questions.

I am calling following line in a Test class:

building.floor(3).waitForElevator();

My Building class has following method which returns the floor object from an array (floors) for given floorNumber.

ArrayList<Floor> floors = new ArrayList<Floor>();

public Floor floor(int floorNumber) {
    return floors.get(floorNumber);
}

My Floor class has waitForElevator() method. In my Floor class I also have an array of length 7 called passengerWaiting. Whenever waitForElevator() is called, I would like to access the correct floorNumber in passengerWaiting array and change its value.

What I am struggling with is when building.floor(3).waitForElevator() is called, how do I access the index (3 in this example) from Floor class.

Thanks for all the help in advance.

Upvotes: 1

Views: 221

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

You could store the value in a class instance variable and make it accessible via an accessor.

public class Building{
    private int floor = 0;

    private ArrayList<Floor> floors = new ArrayList<Floor>();

    public Buliding(){
        Floor floor1 = new Floor(this);
        this.floors.add(floor1);
    }

    public Floor floor(int floorNumber) {
        this.floor = floorNumber;
        return floors.get(floorNumber);
    }

    public int getFloor(){
        return floor;
    }
}

If you add a constructor for Floor that accepts an instance of building and stores it as an instance variable you can access floor at any time.

public class Floor{
   private Building building;

   public Floor(Building building){
       this.building = building;
   }

   public void waitForElevator(){
       int floor = this.building.getFloor();
   }
}

Another Solution

Simply pass the int to waitForElevator as an argument.

public class Floor{

   public void waitForElevator(int floor){
       System.out.println(floor);
   }
}

//Usage
building.floor(3).waitForElevator(3);

Note This solution is not as great because the client could invoke as building.floor(3).waitForElevator(4);

Upvotes: 2

user3033745
user3033745

Reputation: 103

To solve your current problem, I would suggest having each floor keep an int of which floor it is.

However, that seems like code smell to me, so I must ask why you need to do it this way. Could you possibly implement it such that you could just call building.waitForElevator(3)? Another refactoring would be to, rather than have one passengerWaiting ArrayList, have an int value for passengerWaiting in the Floor class, and just change that on each call to waitForElevator.

If you would post your full problem, I could give more helpful of suggestions, I'm guessing here based on the snippets you posted.

Upvotes: 0

Related Questions