0

我在教科书“Java by Dissection”中看到了这段代码,但不明白它到底做了什么。教科书几乎没有解释任何关于这段代码的内容,除了说它实现了一个嵌套类。但我想了解它的实际作用。

我想了解这段代码的原因是因为我试图创建一个 main 来声明/实例化 MyList 类的值为 1-10 的对象。然后在顶部添加一些数字并从我想要的任何地方删除一些。谁能帮我解决这个问题?

我不明白的主要部分是嵌套类 - ListedElement。

public class MyList {
  private ListElement head, tail; //Forward declaration
  void add(Object value) {
    if (tail != null) {
      tail.next = new ListElement(value);
      tail = tail.next;
    }
    else {
      head = tail = new ListElement(value);
    }
  }
  Object remove() 
  {
    assert head != null; // don't remove on empty list
    Object result = head.value;
    head = head.next;
    if (head == null) { //was that the last?
      tail = null;
    }
    return result;
  }
  //Nested class needed only in the implementation of MyList
  private class ListElement {
    ListElement(Object value) {this.value = value;}
    Object value;
    ListElement next; //defaults to null as desired
  }
}
4

1 回答 1

1

让我们从基础开始:MyList 是一个类,它是 Java 中的一个代码单元。在这个类中,你有:

  • 方法:添加、删除
  • 一个内部类:ListElement
  • 一些字段:head,tail,均为 ListElement 类型

在任何类中,“东西”通常在您调用方法时发生。在这里,有两个,他们都按照他们所说的去做。

解释它的最好方法可能是实际演示如何在代码中使用它:

public static void main(String[] args) {
    MyList anInstance = new MyList(); // creates an instance of the MyList class
    // note that at this point, the instance is created, but because there is no constructor method, the fields (head, tail) are both null

    String someValue = "A list element";
    anInstance.add(someValue); // add an element to the list
    // if you step through the add method, you'll see that the value coming in is a String ("A list element"), but nothing has been initialized yet (head, tail are both null)
    // So you'd go to the "else" bit of the logic in the add method, which initializes the head and tail element to the same object that you passed in.  So now your list contains one item ("A list element");

    String anotherValue = "Another value";
    anInstance.add(anotherValue); // add a second element to the list
    // now the path through the add method is different, because your head and tail elements have been initialized, so set the tail.next value to the new element, and then have tail be this new value.
    // so the head is "A list element" and the tail is "Another value" at this point, and the head's next field is "Another value" (this is the linking part of a linked list)

    // from here, you could add more elements, or you could remove elements.  The remove method is pretty straight forward as well -- it removes from the front of the list (note the part of the code that returns the head, and then updates the head value to point to the next item in the list.

}

希望这能让您开始了解这里发生的事情,如果其中任何一个不够清楚,请务必提出更多问题。

于 2013-09-23T17:47:09.537 回答