【问题标题】:How do we efficiently iterate a list of objects from the same object class?我们如何有效地迭代来自同一对象类的对象列表?
【发布时间】:2022-01-13 11:11:41
【问题描述】:

我们有这门课

public class A {

    private String someVariable;
    private List<A> innerObjects;

    /**
    * setters & getters...
    *
    */
}

假设我们不知道 innerObjects 中有多少对象,我们如何以最佳方式手动迭代这个对象?主要问题将在内部列表上,因为它可能还有另一个列表和另一个列表,等等......

【问题讨论】:

  • 这个 ia 树结构。处理非常广泛。只需递归迭代。如果您这样做,广度优先或深度优先乍一看并不重要。
  • 由于不知道深度,所以只能使用递归。
  • “既然你不知道深度,你就必须使用递归。” - 我不相信这是正确的。不知道深度并不要求使用递归来访问所有元素。
  • 是的,你完全正确,我的错。

标签: java algorithm


【解决方案1】:

要访问每个嵌套节点,您可以进行树遍历。有多种遍历顺序可供选择:

  • 深度优先,预购
  • 深度优先,后序
  • 广度优先
  • ...

这里是一些深度优先的示例代码,这些someVariable 字符串的预排序打印,每个都按树中的深度缩进,以及另一个执行 deep 的函数整个对象结构的副本

import java.util.*;

public class A {
    private String someVariable;
    private List<A> innerObjects;

    public A(String text) {
        someVariable = text;
        innerObjects = new ArrayList<A>();
    }

    public A add(String text) {
        return add(new A(text));
    }

    public A add(A object) {
        innerObjects.add(object);
        return object;
    }

    public A deepCopy() {
        A object = new A(someVariable);
        for (A inner : innerObjects) {
            object.add(inner.deepCopy());
        }
        return object;
    }

    public void deepPrint() {
        deepPrint("");
    }
    public void deepPrint(String prefix) {
        System.out.println(prefix + someVariable);
        for (A object : innerObjects) {
            object.deepPrint(prefix + "  ");
        }
    }
}

还有一些驱动代码来测试这个:

    public static void main(String[] args) {
        A root = new A("world");
        A europe = root.add("Europe");
        europe.add("Germany");
        europe.add("France");
        A northAmerica = root.add("North America");
        northAmerica.add("United States");
        northAmerica.add("Canada");
        A copy = root.deepCopy();
        copy.deepPrint();
    }

【讨论】:

  • 我只想通过迭代所有内容手动创建一个深层副本,并将值传递给另一个 A 引用。对象的序列化器后跟反序列化器方法也可以,但我想手动实现
  • “我想手动制作”:那么你尝试过我展示的这种编码模式吗?
  • 添加了执行深拷贝的方法。让我知道这是否是您想要的。
  • 它有效;非常感谢!
【解决方案2】:

你不能比O(n)更有效地迭代一个列表,这是肯定的。

因此,您可以创建一个方法来迭代列表并做一些事情(基本上,您甚至可以在那里提供一个实现您的业务逻辑的函数)并且如果 inner A 包含一个列表然后再次递归调用对象上的方法

这种方法的一个简单例子是:

String concatenateAllVariables(String current) {
    if(innerObjects != null) { // this and the fact loop won't start when the list will be empty is our "stop condition"
        for(A a: innerObjects) {
            current += a.concatenateAllVariables(""); // this is recursive call
        }
    }
    current += someVariable; // where this line (before or after processing children) shoud be is due to traversal algorithm
    return current;
}

另请阅读:

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2018-11-17
    • 2017-08-17
    • 2022-10-19
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多