有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何修改列表中的对象?在迭代时扩展MyObject>?

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

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


共 (3) 个答案

  1. # 1 楼答案

    您根本不需要调用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);
       }
    }
    
  2. # 2 楼答案

    你只需要设置标签。在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.not(e->e.getLabel().contains("/")

  3. # 3 楼答案

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

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

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

    另外,不需要通过迭代器设置对象,因为您在Java中使用对Object的引用,当您编辑对象时,每个有指向该对象的指针的人也会看到更改。要了解更多信息,你可以阅读这篇文章: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