Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 172
  • Last Modified:

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
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
  • 2
  • 2
  • 2
2 Solutions
 
CEHJCommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
objectsCommented:
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now