theTuxRacer theTuxRacer - 1 month ago 7
Java Question

Access object.variable in an array of objects

I need help with this piece of code.

public class ParkingLot {

static int MAX = 5;
static Car[] Slot = new Car[MAX];

public static void main(String[] args) {


Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");

}

public static void Allot() {
for (int i = 0; i <= Slot.length; i++) {
System.out.println(Slot.getNo);

}
}


I am storing a
Car
Object in
Slot
. I wish to print/access the
No
and
Colour
of the car stored in slot. How do I go about doing that?

Answer

Well, if car has a public property, or a public getter method (this is preferable - getNumber() and getColour()), you can call them while iterating the array with the for-each loop:

for (Car car : slot) {
    System.out.println(car.getColour());
}

Note that I've lowercased slot - variable names in Java should be lowercase. I'd also advise for naming the array with plural name - i.e. slots.

Note also that the way of iteration provided by others is possible, but not recommended for the basic case of iterating the whole array. Effective Java (Bloch) recommends using the foreach loop whenever possible.