Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.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_Class_Object - Fatal编程技术网

Java 在对象中定义对象是否有更简单的方法?

Java 在对象中定义对象是否有更简单的方法?,java,class,object,Java,Class,Object,所以我有一节课 public class Box { int index; static int amount; Box thisbox; Cargo thiscargo; Box(){ index = amount; amount++; } } 在另一个类中,我将定义框: public class dostuff { public static void main(String[] args) throw

所以我有一节课

public class Box {
    int index;
    static int amount;
    Box thisbox;
    Cargo thiscargo;
    Box(){
        index = amount;
        amount++;
    }
}
在另一个类中,我将定义框:

public class dostuff {
    public static void main(String[] args) throws NoSuchMethodException {
        Box box = new Box();
        box.thisbox = new Box();
        box.thisbox.thisbox = new Box();
        box.thisbox.thisbox.thisbox = new Box();
        box.thisbox.thisbox.thisbox.thisbox = new Box();
    }

}
正如你所知,这个盒子。这个盒子。这个盒子。这个盒子。这个盒子。这个盒子变得很烦人。我想知道是否可以更轻松地循环访问box.thisbox.thisbox.thisbox,而不必重复.thisbox三次。可能会有这样一种情况,我必须在框内定义30个框,我不想复制和粘贴“thisbox”内容太多次。我真的很想得到一些帮助。谢谢
编辑:我不能使用数组列表。不要问…

你可以写一个递归方法,它可以深入到某个层次

像这样的

public Box getNthBox(Box box, int depth) {
    If (depth == 0) {
        return box;
    } 

    return getNthBox(box.getBox(), depth - 1);
}

您需要一个getBox()方法来返回Box字段

只要您知道终止点,即直到您想继续创建长方体对象时,您可以通过多种方式来完成。这是实现这一目标的方法之一

使用递归

public static void main(String[] args) {
    Box box = new Box();
    createBox(box);
}

public static void createBox(Box box) {
        while(box.amount != 10){
        box.thisbox = new Box();
        createBox(box.thisbox);
    }
}

看起来您可能需要一个LinkedList