javaiterationlistiterator

How to modify objects in a List<? extends MyObject> while iterating?


I am trying to modify a field in select objects in a List but I am unable to find a way to do so, using plain Iterator because it has no set() method.

I tried using ArrayListIterator that provides a set() method, but this throws a casting exception. Is there way to workaround this?

   Iterator it = topContainer.subList.iterator();
   while (it.hasNext()) {
      MyObject curObj = (MyObject) it.next();
      if ( !curObj.getLabel().contains("/") ) {
           String newLabel = curObj.getLabel() + "/";
           curObj.setLabel(newLabel);
           ((ArrayListIterator) it).set(curObj)
       }
    }

I expect the original current object in the list to be set without incident, but instead I am getting this exception:

java.util.ArrayList$itr cannot be cast to org.apache.commons.collections.iterators.ArrayListIterator

What is the proper way of accomplishing what I would like to do?


Solution

  • You do not need to call set at all. You can just call setLabel on curObj:

    // please, don't use raw types!
    Iterator<? extends MyObject> it = topContainer.subList.iterator();
    while (it.hasNext()) {
       MyObject curObj = it.next();
       if ( !curObj.getLabel().contains("/") ) {
           String newLabel = curObj.getLabel() + "/";
           curObj.setLabel(newLabel);
       }
    }