Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.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 - Fatal编程技术网

Java 对象包含对象的列表。查找最大深度

Java 对象包含对象的列表。查找最大深度,java,Java,我有以下课程: class A { List<A> as; } 我需要返回3 我尝试了递归方法,递归深度计算: public static int computeDepth(A a) { int maxDepth = 0; for(A innerA : a.getAs()) { int depth = computeDepth(innerA); if(depth > maxDepth) m

我有以下课程:

class A {
    List<A> as;
}
我需要返回3


我尝试了递归方法,递归深度计算:

public static int computeDepth(A a)
{
    int maxDepth = 0;
    for(A innerA : a.getAs())
    {
        int depth = computeDepth(innerA);
        if(depth > maxDepth)
            maxDepth = depth;
    }
    return maxDepth + 1;
}
使用Java 8流:

class A {
    List<A> as;

    public int getDepth() {
        return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
    }
}

你能展示你已经尝试过的吗?你需要说明
secondA.add(firstA)?在类A中设置静态变量max_Size=3。在addA方法中,检查大小是否等于或大于max_Size(如果大于max_Size),然后替换或删除,或者执行任何您想要的操作to@bradimus不。不会有这种情况。我不能向
类添加方法,但我知道如何使用它。现在我要试着了解这个想法。谢谢你,伙计。如果这不是a的方法,我会加上一个解释。
class A {
    List<A> as;

    public int getDepth() {
        return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
    }
}
public class MyClass {
    public static int getDepth(A a) {
        return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
    }
}