iterator help + Arraylist

• 05-07-2013, 03:20 AM
NoobieCode
iterator help + Arraylist
i have an ArrayList<Fish> fish. I was wondering how to
use the iterator method. I want to go through each element
in the arraylist and do the following:

isAlive is a boolean method that checks if the fist is size 0 or not. If it is then it returns true.
shrink method just takes the size of a fish and decrease is by two.

I have written these methods already.

I was wondering how to write the iterator/ use iterator...im new to this.. I know in arrays you
had to create a for loop and iterate through each element that way.

Thanks for help.

Code:

```         /** Iterates through fish list.  For each fish that isAlive, shrinks the fish by         * invoking it's "shrink" method. */         public void shrinkFish() {                 throw new RuntimeException("You code this!");                                         }         }```
• 05-07-2013, 03:31 AM
monkeyjr97
Re: iterator help + Arraylist
you need to use a for each loop for your arrayList, i don't now what the isAlive is but i assume a boolean variable. So in this case you need to:

1, do a for each loop through the ArrayList<Fish>
2, check to see if the current Fish is alive
3, if it is call the shrink method
4, if it isnt alive do nothing

steps 3,4 can be handled using the same if statement.
• 05-07-2013, 03:42 AM
jim829
Re: iterator help + Arraylist
Since ArrayList also implements iterable (which means you can get an iterator via the iterator() method) you can use the shorthand form of iteration:

Code:

```for (Fish f : fish) { // do something with f }```
You can also do the following:

Code:

```Iterator<Fish> it = fish.iterator(); Fish f; while (it.hasNext()) {     f = it.next();   // do something with f }```
Regards,
Jim
• 05-07-2013, 03:46 AM
NoobieCode
Re: iterator help + Arraylist
Thank you all. I wasn't sure how to implement the syntax part. Thanks
• 05-07-2013, 03:51 AM
NoobieCode
Re: iterator help + Arraylist
isAlive method is a Boolean method...it returns true if the fish size is greater than zero..

How do i go about checking each element is alive??
• 05-07-2013, 03:59 AM
NoobieCode
Re: iterator help + Arraylist
Nevermind. i figured it out!