Results 1 to 2 of 2
- 05-11-2012, 03:25 AM #1
Member
- Join Date
- May 2012
- Posts
- 1
- Rep Power
- 0
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:
Java Code://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. while(iterator_farm.hasNext()) { System.out.printf( iterator_farm.next().toString() + " "); System.out.printf( iterator_farm.next().toString() + "\n"); }
- 05-11-2012, 05:31 AM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 762
- Rep Power
- 14
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.Website: Learn Java by Examples
Similar Threads
-
Change file attributes
By Pratyush13 in forum New To JavaReplies: 0Last Post: 11-02-2011, 05:18 AM -
Modifying an object's attributes by using another object's method
By skybluenova in forum New To JavaReplies: 3Last Post: 09-08-2011, 12:53 PM -
How to change controls attributes
By varesa in forum SWT / JFaceReplies: 3Last Post: 06-23-2011, 07:41 PM -
Using Event handlers functions to change attributes used to test conditions
By Sneaky Fox in forum AWT / SwingReplies: 9Last Post: 01-20-2011, 05:01 PM -
Classes with object attributes
By RRasco in forum New To JavaReplies: 5Last Post: 11-25-2008, 01:07 AM
Bookmarks