Iterating over Java object collections - how can I mutate the current object?

I will use an iterator to scroll through a collection of objects in Java. I am a bit confused about using Iterator (used for every loop). let's 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 then to set the source object, I formed an iterator equal to the list of this object that I am creating (the list is not shown above, but I just realized that I would need it).

But it would be much easier if I did not have to create a new Object to do all this. Is there a way to get the current object and change it?

+5
source share
2 answers

Try the following:

for(Organization org : orgs)
    org.setChildOrgsTree(generateOrgChildTree(org, new ArrayList<Organization>());
+4

List Queue, . , , , , Iterator.next(). , , , ...

, , Iterator, Iterator.remove(), , , . , , ConcurrentModificationException , .

, Set, , , : Set , . , , hashCode(), , HashSet...

for-each Java - Iterator. Iterator.remove(), for-each .

+3

All Articles