gpt4 book ai didi

java - 如何实例化 MyList 对象

转载 作者:行者123 更新时间:2023-12-01 14:05:07 24 4
gpt4 key购买 nike

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

我想理解这段代码的原因是因为我试图创建一个 main 来声明/实例化具有值 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
}
}

最佳答案

让我们从基础开始: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.

}

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

关于java - 如何实例化 MyList 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18965327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com