简体   繁体   中英

understand iterating through arraylist

Hi everyone I am doing homework and I don't understand one part of it.I have implemented it but it is not working as supposed so. It says:

Iterate through the ArrayList of Pizza objects calling the toString() method of each object, adding the return value of the method call plus a newline character to the String called list.

And here is what I have done

for(int i=0; i<myList.size()l i++)
{
//myList is arraylist of type Pizza
   list +=myList.toString() + "\n";
}

If anyone can say whether my implementation is correct, it will be great.

您需要调用ArrayList#get()方法which will return the element at the specified position in this list方法which will return the element at the specified position in this list

list +=myList.get(i).toString() + "\n";

You need to iterate over the list elements using the for( : ) syntax, not the for( ; ; ) syntax:

for (Pizza item : myList ) {
   list += item.toString() + "\n";
}

In situations when you want to go through all elements of the list, you do not need an index variable. The for each syntax added in Java 5 lets you go through the list more easily.

This is not correct. ArrayList is an object that has its own methods.

You can't access its members via myList[ index ]... you have to call its get() method...

list += myList.get(i);

this is assuming that list is a String that you're just concatonating every item of myList to (which sounds like something you probably don't want to do either, but I can't say what your actual objective is).

as dasblinkenlight points out the other (possibly more elegant) way to do this is to skip the for(;;) loop and use the for (:) loop where you iterate through the list and just grab each item into its own variable on the fly. The downside to that approach is that if for some reason you do need to know what the items index in the array list is, you don't have that information handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM