返回 class 的副本

Returning a copy of class

假设我有一个链表。

class LinkedList {
...
    private Node head;
    private int length;

    private class Node {
        Element element;
        Node next;
    }

    public LinkedList tail() { }
}

我将如何实施 tail 以便:

  1. 它 returns LinkedList,没有 Head 元素。
  2. 对原始 LinkedList 所做的任何更改都会反映在 tail returns

我尝试过的事情:

  // This fails because it creates a new LinkedList, and modifying 'this' won't affect the new LinkedList.
  public LinkedList tail() {
    LinkedList temp = new LinkedList();
    temp.head = this.head.next;
    temp.length = this.length - 1;
    return temp;
  }

  // This fails because it modifies the original LinkedList.
  public LinkedList tail() {
    LinkedList temp = this;
    temp.head = this.head.next;
    temp.length = this.length - 1;
    return temp;
  }

基本上,我需要 tail 指向 head.next

创建一个 LinkedList 的子类来包装原始的:

class TailList extends LinkedList {
  LinkedList list;
  TailList(LinkedList list) { this.list=list;}
  Node head() { return list.head().next; }
  int length() { return list.length()-1;}
}

当然得先把LinkedList中的字段封装起来。我实际上会将 LinkedList 变成一个接口,将您当前的 LinkedList 变成 LinkedListImpl implements LinkedList 并如上所述添加 TailList。

class LinkedListImpl implements LinkedList{
  ...
  LinkedList tail(){ return new TailList(this); }
  ...
}

顺便说一句。我建议考虑不可变数据结构...