访问对象数组中的object.variable

时间:2010-06-26 07:35:03

标签: java

我需要这段代码的帮助。

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);

    }
}

我在Car中存储Slot对象。我希望打印/访问存储在插槽中的汽车的NoColour。我该怎么做呢?

5 个答案:

答案 0 :(得分:2)

好吧,如果car有公共属性或公共getter方法(最好是getNumber()getColour()),你可以在使用for迭代数组时调用它们 - 每个循环:

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

请注意,我已经小写slot - Java中的变量名称应该是小写的。我还建议用多个名称命名数组 - 即slots

另请注意,其他人提供的迭代方式是可行的,但不推荐用于迭代整个数组的基本情况。 Effective Java (Bloch)建议尽可能使用foreach循环。

答案 1 :(得分:1)

使用[]表示法:

public static void Allot() {
    Car car;
    for (int i = 0; i <= Slot.length; i++) {
        // Get the car at this position in the array
        car = Slot[i];

        // Make sure it isn't null, since the array may not have
        // a full set of cars
        if (car != null) {
            // Use the car reference
            System.out.println(car.getNo());
        }
    }
}

(我假设getNo是一个方法,而不是一个属性。)

例如,Slot[0]为您提供了第一个Car,您可以从中访问Car的属性和方法,因此Slot[i]会在i为您提供汽车1}}位置。 (在上面我使用了一个临时变量来存储汽车,但你可以直接使用Slot[i].getNo(),这没关系。我只是不想重复数组查找,即使是通过HotSpot [Sun JVM]即使我这样做也会优化它。)

答案 2 :(得分:1)

很抱歉这么晚。我注意到上面的答案中缺少一些东西,所以这里是所述问题的完整解决方案。

这是ParkingLot类,调用Allot()方法。

公共类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");

    Allot();

}

public static void Allot() {

    for (int i = 0; i < Slot.length; i++) {

        if (Slot[i] != null) {
            System.out.println(Slot[i].getNo()+" , "+Slot[i].getColor());
        }
    }
}

}

使用getNo()和getColor()方法的Car类。

公共类汽车{

private String Number;
private String Color;

Car (String Number, String Color){
    this.Number = Number;
    this.Color = Color;

}

public String getNo(){
 return Number;   
}

public String getColor(){
    return Color;
}

}

答案 3 :(得分:0)

class Car{
    String number;
    String color;

    public Car(String number, String color) {
        this.number = number;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "number='" + number + '\'' +
                ", color='" + color + '\'' +
                '}';
    }
}

class Test{
    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");

        for (Car car : Slot)
            System.out.println(car);
    }

}

答案 4 :(得分:0)

您可以像这样

创建和访问对象的对象数组
Object[] row={"xx","xcxcx"};

Object[] cotainer = {row,row,row};

for(int a=0;a<cotainer.length;a++){

    Object[] obj = (Object[])cotainer[a];

}