如何实例化MyList对象

时间:2013-09-23 17:29:08

标签: java

我在教科书“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
  }
}

1 个答案:

答案 0 :(得分: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.

}

希望这可以让你开始了解这里发生的事情,并且如果有任何问题不够清楚,请务必提出更多问题。