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?
Try this:
for(Organization org : orgs)
org.setChildOrgsTree(generateOrgChildTree(org, new ArrayList<Organization>());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With