如何修改 List<?在迭代时扩展 MyObject>?

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

我正在尝试修改列表中 select 个对象中的一个字段,但我无法找到这样做的方法,因为它没有 set() 方法,所以我使用普通的迭代器。

我尝试使用提供 set() 方法的 ArrayListIterator,但这会引发转换异常。有办法解决这个问题吗?

   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)
       }
    }

我希望列表中的原始当前对象能够顺利设置,但我却收到此异常:

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

完成我想做的事情的正确方法是什么?

您根本不需要调用 set。您可以在 curObj:

上调用 setLabel
// 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);
   }
}

正确的方法如下(不适用于低于 1.5 的 java 版本):

for(MyObject curObj : topContainer.subList){
    if (!curObj.getLabel().contains("/")) {
       String newLabel = curObj.getLabel() + "/";
       curObj.setLabel(newLabel);
    }
}

这是一个增强的 for 循环,它也会调用迭代器,但您看不到它。

也不需要通过迭代器设置对象,因为您正在处理 Java 中对 Object 的引用,当您编辑一个对象时,每个有指向该对象的指针对象,也会看到变化。如需更多信息,您可以阅读这篇精彩的文章 post:Is Java “pass-by-reference” or “pass-by-value”?

If you can't use Java 5, then you're missing out big time. The current java version is 11. So you should really, really, really, upgrade your JDK

您只需设置标签即可。在 JAVA 11 中,您可以使用流。它使您的代码更具可读性。

List<MyObject> list = topContainer.subList;
list
    .stream()
    .filter(Predicate.not(e->e.getLabel().contains("/")))
    .forEach(e->e.setLabel(e.getLabel()+"/"));

在java8中你可以使用

(!e->e.getLabel().contains("/"))

而不是

Predicate.not(e->e.getLabel().contains("/")