How to change object attributes in an ArrayList
Heres my case:
I have an arraylist called farm.
In this farm I have stored Cows with Age, Color and Sex.
Using an Iterator how would I change all my cows that are 4 years old into the color red, and change sex into male?
I only know how to use the next() method to access what an iterator points at, but I want it to stay put, so I can do otherthings to the object its pointing at.
Heres my problem in a simpler situation:
//iterator_farm is an iterator to a farm which is just an arraylist with Integers,
//how would I print the same number twice without using a var to store it at.
System.out.printf( iterator_farm.next().toString() + " ");
System.out.printf( iterator_farm.next().toString() + "\n");
Re: How to change object attributes in an ArrayList
If you look at the API documentation of the next() method of Iterator you will see that it return an Object. So if you store some Cows in the iterator then it will give you the Cow object back. And then you can just do everything your want with your Cow, such as check their age, and when it 4 years old change their color into red, etc.
If you didn't specifically say that you'll store a cow in the collection you need to do object casting in here.