Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While iterating over a collections of Java objects--how can I mutate current object?

Tags:

java

iterator

I will be using an iterator to loop through a collection of objects in Java. I am a little confused about using an Iterator however (used to using for each loop). let say I have code like this:

Iterator<Organization> orgIter = orgs.iterator();
while (orgIter.hasNext()) {
    Organization orgObj = orgIter.next();
    orgObj.setChildOrgsTree(generateOrgChildTree(orgObj, new ArrayList<Organization>()));
}

I create a new object and then change the fields inside the object. My plan was to then set the original object I formed the iteroter out equal to a List of this Object that I create (List is not shown above, but I just figured out that I would need it).

But it would be so much easier if I didn't have to create a new Object to do all of this. Is there a way I can get the current object and mutate that?

like image 444
SoftwareSavant Avatar asked Jun 21 '12 12:06

SoftwareSavant


2 Answers

Try this:

for(Organization org : orgs)
    org.setChildOrgsTree(generateOrgChildTree(org, new ArrayList<Organization>());
like image 114
Angel Avatar answered Oct 04 '22 22:10

Angel


If your iterator iterates over a List or Queue instance, then there are fewer restrictions. As long as you do not change the structure of the list, you can do whatever you wish with the object returned by Iterator.next(). Of course, the class of that specific object should allow it to be modified, but I presume that you can add the necessary code...

On the other hand, the only list structure modification that is allowed without invalidating the Iterator object, is to remove the current element using Iterator.remove(), which, incidentally, is an optional operation. If you try to modify the list directly then the iterator will be invalidated and you will get a ConcurrentModificationException the next time you try to use it.

Additionally, if you are iterating over a Set, you are generally far more constrained: depending on the details of the actual Set implemenation, you are not generally able to modify arbitrary fields in your objects. For example, the value returned by hashCode() should not change once an object has been inserted in a HashSet...

As a sidenote, for-each loops in Java are just syntactic sugar for using an Iterator. If you are not going to use Iterator.remove(), just use a for-each loop instead of the explicity iterator and be done with it.

like image 35
thkala Avatar answered Oct 04 '22 20:10

thkala