问题
I am trying to access a variable that is stores as part of an object that is in an array. However that array is in an arraylist. How can access that variable? To make it clear, I have a car object that has speed. I placed 4 cars in an array. And that array is duplicated and put in an arraylist.
public int getSpeedOfCarA (int index) {//used to access the variable speed in an array
return garage [index].getSpeed ();
}
Now I was trying this but got stuck.
public int getSpeedOfCarB(int n){
carSpeeds.get(...); //not sure what to use here.
}
回答1:
To access things inside of other things, simply chain the access syntax together. For the example of getting a field inside an object inside an array inside a List
, you would simply use
list.get(pos)[arrayPos].fieldName
You may be misunderstanding how ArrayList works however: When working with it, you never see the array, and in fact as far as syntax is concerned it doesn't matter whether it's implemented as an Array or as a LinkedList or whatever else. If so, you need not use any array operator, as the get
method will do that for you:
list.get(pos).fieldName
回答2:
I prefer to use an Iterator to access the car object in the list.
ArrayList<Car> list = new ArrayList<Car>();
Iterator i = list.iterator();
while(i.hasNext()){
Car car = i.next();
}
回答3:
Use,
for(Car[] carArrays : listOfCarArrays) {
for (Car car : carArrays) {
//do something with car like car.getSpeed();
}
}
来源:https://stackoverflow.com/questions/29001953/array-inside-arraylist-access