【发布时间】:2021-02-05 13:40:44
【问题描述】:
我是编程新手,遇到了访问问题。 目前我尝试练习 LinkedList - 通过自己创建一个然后使用它。
我在同一个目录中有 3 个类 - 自定义的“MyLinkedList”,另一个自定义的,我称之为“月”和“主”。我的想法是创建 12 个月份对象类,因为每个对象都有 3 个字段并将它们添加到 LinkedList - 我做到了。现在我有问题,当我想检索某个对象字段的某个值时。我得到了对象的地址,但不知道如何到达这个地址后面的值。
示例 - 我创建了一个包含 12 个节点的 MyLinkedList,并在每个节点中放置了一个 Month 类型的对象。稍后我想说获取名为 'season' of March 的字段(Month 类型的对象),它存储在我的 Linked List 中。
我做什么 - 访问我的 LinkedList 中名为“item”的字段,该字段包含一个 Month 类型的对象(对象的地址)。现在我想不通,我该如何进一步,到达该地址后面的对象并检索该对象的字段保留的值。
我的理解是 - 1)我在堆栈中有一个名为“myList”的引用变量,其中包含堆中“MyLinkedList”类型的对象的地址。 2) 内存中与该地址对应的位置保存了 12 个“节点”的另外 12 个地址。 3)每个节点(一块内存),保存一个对象“月”的地址。 4)内存中对应于月份地址的位置保存了(对象的)3个字段的地址。 5) 在最后一个地址(字段的)后面放置了所需的值。所以我只能达到第 3 步,但无法继续。您能建议如何进行下一步。
我把这3种方法的一些代码:
这是我的代码:
public class MyLinkedList {
private class Node{
Object item;
Node next;
Node(Object item){
this.item = item;
this.next = null;
}
Node(Object item, Node next){
this.item = item;
this.next = next;
}
}
private Node head;
private Node tail;
private int count;
public void addNode(Object element){
Node newNode = new Node(element);
if(head == null){
head = newNode;
head.next = tail;
tail = head;
}
else {
tail.next = newNode;
tail = newNode;
}
count++;
}
public void printList(){
Node currentNode = head;
while(currentNode != null){
if(currentNode.next != null){
System.out.print(currentNode.item + ", ");
}
else {
System.out.println(currentNode.item + ";");
}
currentNode = currentNode.next;
}
}
}
public class Month {
private String season;
private int length;
public int index;
public Month(int index){
this.index = index;
}
public String getSeason(){
return season;
}
public void setSeason(String season){
this.season = season;
}
public int getLength(){
return length;
}
public void setLength(int length){
this.length = length;
}
}
public class Main {
public static void main(String[] args) {
Month January = new Month(0);
Month February = new Month(1);
Month March = new Month(2);
/*
....more of the same here
*/
January.setLength(31);
February.setLength(28);
March.setLength(31);
/*
....more of the same here
*/
January.setSeason("Winter");
February.setSeason("Winter");
March.setSeason("Spring");
/*
....more of the same here
*/
MyLinkedList myList = new MyLinkedList();
myList.addNode(January);
myList.addNode(February);
myList.addNode(March);
/*
....more of the same here
*/
System.out.println("Initially created list:");
myList.printList();
System.out.println();
}
【问题讨论】:
-
你在哪里初始化
myList?在Main类中使用它,但不要声明或初始化它。 -
感谢您的来信。我刚刚剪掉了部分代码,但错过了……我在 Main 方法中声明并初始化 myList,就在将元素添加到列表之前。现在它被编辑了。
标签: java object linked-list reference field