2

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.
}
3
  • Presumably by iterating the Car(s) in the List... I assume getSpeedOfCarA(int) is in class Car, and also why do you need a getSpeedOfCarB(int)... what is that for? Commented Mar 12, 2015 at 4:40
  • Can you please post your full code? Commented Mar 12, 2015 at 4:42
  • the first is an array of cars from a car class. It has speed as a variable. The second should be an arraylist of arrays of cars. Commented Mar 12, 2015 at 4:50

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Use,

for(Car[] carArrays : listOfCarArrays) {
    for (Car car : carArrays) {
        //do something with car like car.getSpeed();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.