0

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.

3 Answers 3

4

You need to call ArrayList#get() method which will return the element at the specified position in this list.

list +=myList.get(i).toString() + "\n";
Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Sometimes, you need to use the index variable, for example, printing "item at index " + i + ": " + list.get(i). BTW, for( : ) syntax is called enhanced-for loop in Java.
3

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.

1 Comment

yes list is String, and I am reading data from file, and storing it in the string obj list

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.