-2

我有这个 java 类,但是在 printLista 方法中,我正在验证属性是否为空,但我不知道为什么即使不为空,它也不会进入循环,实际上,当我没有定义时,它会向后工作属性,它是 null 进入循环

public class App {
    public static void main(String[] args) {
        Lista myList = new Lista(3);
        
        myList.setCola(new Lista(8));

        myList.printLista();
    }
}


public class Lista{
    public int head;
    public Lista cola;

    public Lista(int head){
        this.head = head;
        this.cola = null;
    }

    public int getHead(){
        return this.head;
    }

    public Lista getCola(){
        return this.cola;
    }

    public void setCola(Lista cola){
        this.cola = cola;
    }

    public void printLista(){

        Lista nodo = this.getCola();

        while(nodo.cola != null){
            System.out.println(nodo.getHead());
            nodo = nodo.getCola();
        }
    }
}
4

1 回答 1

0

Lista myList = new Lista(3); 这一行创建了一个新的 Lista 对象,其头部为 3,可乐为 null。

myList.setCola(new Lista(8)); 此行首先创建一个新的 Lista 对象,其头部为 8,可乐为 null。然后它将这个新对象设置为 myList 的可乐。

Lista nodo = this.getCola(); printLista 方法中的这一行将获取 myLista 的 cola,这是在步骤 2 中创建的对象。因此 nodo 将具有 head 8 和 cola null。

由于 nodo.cola 为 null,因此不会执行 while 循环。

于 2020-12-08T06:10:03.357 回答