令人困惑的Java语法

时间:2017-12-28 00:30:13

标签: java syntax constructor linked-list simplify

我有一段我难以理解的代码。代码片段本身是双向链表的构造函数,这很好;但是,最后一行说:(head = head.next).previous = null;这应该会删除用于从阵列a添加节点的临时节点。但它是如何工作的?如果有人可以把它分解成明确的,单独的行,那将非常有帮助。 这是构造函数:

// standard constructor
public DoublyLinkedList() {
    head = tail = null;
    numElements = 0;
    changes = 0;
}

// constructor
public DoublyLinkedList(T[] a) {
    this();  // call the standard constructor

    Objects.requireNonNull(a, "a is null!");

    head = tail = new Node<>(null);  // a temporary node

    for (T value : a) {
        if (value != null) {
            tail = tail.next = new Node<>(value, tail, null);  // new node at the back
            numElements++;
      }
    }

    // remove the temporary node
    if (numElements == 0) head = tail = null;
    else (head = head.next).previous = null; // the problematic bit
}

4 个答案:

答案 0 :(得分:0)

head = head.next;
head.previous = null;

答案 1 :(得分:0)

它是这样的:

if (numElements == 0) {
     head = null;
     tail = null;
}
else {
    head = head.next;
    head.previous = null; // the problematic bit
}

人们不应该写原始方式,它会使代码混乱,正如您刚刚发现的那样。

答案 2 :(得分:0)

让我试着为你分解一下。我假设您难以理解的代码部分如下:

else (head = head.next).previous = null; // the problematic bit

首先评估括号内的表达式,这意味着上面的代码段基本上变成了以下内容,就像我之前的其他人已经提到过的那样。

head = head.next; // move onto the next node
head.previous = null;

如果您难以理解上述逻辑,请尝试运行以下代码。在除法运算之前首先评估4 + 2。

System.out.println((4 + 2) / 2);

答案 3 :(得分:0)

第一次使用.previous时需要临时节点。它被放在了头上。然后当它不再需要它从头上移开时。

代码中SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_name IN ( 'post title 1', 'post title 2', 'post title 3', ) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.menu_order, FIELD( wp_posts.post_name, 'post title 1', 'post title 2', 'post title 3', ) LIMIT 0, 9 无法在那里工作的问题,因为它未在循环中设置。

相关问题