Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何修改列表中的对象?_Java_Iteration_Listiterator - Fatal编程技术网

Java 如何修改列表中的对象?

Java 如何修改列表中的对象?,java,iteration,listiterator,Java,Iteration,Listiterator,我试图修改列表中选择对象中的字段,但我无法找到使用普通迭代器进行修改的方法,因为它没有set方法 我尝试使用提供set方法的ArrayListIterator,但这会引发强制转换异常。有办法解决这个问题吗 Iterator it = topContainer.subList.iterator(); while (it.hasNext()) { MyObject curObj = (MyObject) it.next(); if ( !curObj.getLab

我试图修改列表中选择对象中的字段,但我无法找到使用普通迭代器进行修改的方法,因为它没有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强制转换为 org.apache.commons.collections.iterators.arraylisterator

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

您根本不需要调用set。您只需在curObj上调用setLabel:


正确的方法是以下工作不适用于1.5以下的java版本:

for(MyObject curObj : topContainer.subList){
    if (!curObj.getLabel().contains("/")) {
       String newLabel = curObj.getLabel() + "/";
       curObj.setLabel(newLabel);
    }
}
这是一个增强的for循环,它也调用迭代器,但您看不到它

另外,不需要通过迭代器设置对象,因为在Java中使用对对象的引用,当您编辑对象时,每个有指向该对象的指针的人都会看到更改。要了解更多信息,您可以阅读这篇很棒的帖子:

如果您不能使用Java5,那么您就错过了重要的时间。当前的java版本是11。所以你应该真的,真的,真的,升级你的JDK


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

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.note->e.getLabel.contains/

curObj.setLabelnewLabel;应该足够了。您只需要更改对象上的标签,就不需要在listMyObject类中用对象本身覆盖对象。是否有字段标签的setter?setLabel?你想达到什么目的?您可以迭代arraylist并修改对象。您不需要将对象设置为iterator@ernest_k您的建议仅修改通过迭代器从列表中获取的原始对象的副本。我不会修改原件。@内省它会修改原件。MyObject是一个类,对吗?为什么不直接使用topContainer.subList.stream?不需要Iterable,也不需要Lino说的话。另外,如果你真的想要一个迭代器,为什么不仅仅是它呢?forEachRemaining?还有Predicate.not不是来自JDK8,它来自哪里?@Lino its来自Java 11。你可以用!e->e.getLabel.contains/如果您使用的是Java8!e、 getLabel.contains/您是正确的。我根本不需要呼叫set。修改对原始对象有效。我可能错过了迭代器
List<MyObject> list = topContainer.subList;
list
    .stream()
    .filter(Predicate.not(e->e.getLabel().contains("/")))
    .forEach(e->e.setLabel(e.getLabel()+"/"));