list iterator

Hi,

I use iterators with maps pretty often like:

    for (Map.Entry<Integer, String> it: mylist.entrySet()) {
       it.getValue().toString();
    }

how do you do the same with an ArrayList?

Thanks
DJ_AM_JuiceboxAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
for (T t : someList)

(where 'T' is the type)
0
 
objectsCommented:
Heres an example:

ArrayList<String> list = new ArrayList<String>();

for (String s : list}
{
    System.out.println(s);
}

0
 
DJ_AM_JuiceboxAuthor Commented:
Quick question on that, consider:

public class Test
{
    ArrayList<Car> m_cars;

    public ArrayList<Car> getCars()
    {
        return m_cars;
    }
}

public static void main()
{
    Test test = new Test();

    for (Car car : test.getCars())
    {
         ....
    }
}

every time an iteration of the for-loop is done, does it need to call getCars() for any reason? I'm comparing that to:

    for (int i = 0; i < test.getCars().size(); i++) {
          ...
    }

where it would have to call getCars() every iteration.

Thanks
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
objectsConnect With a Mentor Commented:
no it wouldn't (it would use iterator)

>     public ArrayList<Car> getCars()

on a side note, making it return List instead of ArrayList is generally abetter idea.
Allows you to change the List implementation used in your class in the future without affecting users of the class.

    public List<Car> getCars()

0
 
DJ_AM_JuiceboxAuthor Commented:
ok thanks
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.