0

このコードは教科書「Java by Dissection」で見ましたが、正確には何をしているのかわかりません。教科書は、ネストされたクラスを実装していると言う以外に、このコードについてほとんど何も説明していません。しかし、私はそれが実際に何をするのかを理解したいと思っています。

このコードを理解したい理由は、値が 1 ~ 10 の MyList クラスのオブジェクトを宣言/インスタンス化するメインを作成しようとしていたからです。次に、上部にいくつかの数字を追加し、必要な場所からいくつかを削除します. 誰でもこれで私を助けることができますか?

私が理解していない主な部分は、ネストされたクラス - 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 型

どのクラスでも、通常、メソッドを呼び出すと「何か」が発生します。ここには 2 つありますが、どちらも自分の言うことを実行します。

それを説明する最良の方法は、実際にコードでどのように使用できるかを示すことです。

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 に答える