2017-12-18 193 views
-1

我有在Java中保存为对象的汽车,其存储另一数组的数组,它是建立在像这样:访问对象是在交织排列

阵列汽车:

- (Array)Car1 
    - Color 
    - Price 
- (Array)Car2 
    - Color 
    - Price 
- (Array)Car3 
    - Color 
    - Price 

简化代码如下所示:

String color = "yyy"; 
String price = "xxx"; 

String[] Car1 = { color, price }; 
String[] Car2 = { color, price }; 
String[] Car3 = { color, price }; 

String[][] Cars = { Car1, Car2, Car3 }; 

现在,我怎么能访问像Car1颜色交错对象通过阵列Cars现在?

我试图在循环内使用循环,但我无法得到正确的解决方案。

编辑:我知道这将是一个更好的解决方案,使用一个Car类,但我感兴趣的是如何使用这样的交错数组。

+1

为什么“Car”类的颜色和价格属性不? – Kayaman

+3

而不是使用字符串数组,使用类来表示数据。 –

+0

看看编辑 –

回答

1

的颜色,如果你对汽车创建一个类,并与你需要的属性的工作会更好:

public class Car{ 
    private String color; 
    private String price; 

    //constructor, getter and setters 
} 

但是,如果你真的需要在你问的方式,你可以使用:

Cars.get(indexOfCar).get(indexOfList); 
    |  |    | 
    |  |    |> Which String of the List you need 
    |  |  
    |  |> Which Car you need of Cars (Car1, Car2, Car3) 
    | 
    |> The List name 

或者,如果你需要静态数组做到这一点,你可以以同样的方式:

Cars[indexOfCar][indexOfList]; 
0

使用类似下面的类来表示你的汽车。然后Car阵列将完成这项工作。

public class Car { 
    private String color; 
    private Double price; 
    public String getColor() { 
     return color; 
    } 
    public void setColor(String color) { 
     this.color = color; 
    } 
    public Double getPrice() { 
     return price; 
    } 
    public void setPrice(Double price) { 
     this.price = price; 
    } 

} 
+0

没有理由在这里使用'Double'。原始状态很好。 – Michael

0

如果你想进入汽车的性能,你需要做的是这样

Cars.get(<car index>).get(<property index>) 

例如为分享帮助

String colorOfCar1 = Cars.get(0).get(0) 
+0

你注意到'Cars'是一个数组,而不是一个List?那么,在整个问题上的“ArrayList”可能会误导我......我会建议编辑。 –