我是编程新手,遇到了访问问题。 目前我尝试练习 LinkedList - 通过自己创建一个然后使用它。
我在同一个目录中有 3 个类 - 自定义“MyLinkedList”,另一个自定义类,我称之为“Month”和“Main”。我的想法是创建 12 个月类对象,因为每个对象都有 3 个字段并将它们添加到 LinkedList - 我做到了。现在我有问题,当我想检索某个对象字段的某个值时。我得到了对象的地址,但不知道如何获取该地址背后的值。
示例 - 我创建了一个包含 12 个节点的 MyLinkedList,并在每个节点中放置了一个类型为 Month 的对象。稍后我想说获取名为“季节”的三月字段(月类型的对象),它存储在我的链接列表中。
我做什么 - 访问我的 LinkedList 中名为“item”的字段,该字段包含一个类型为 Month 的对象(对象的地址)。现在我想不通,我该如何进一步进行,以到达该地址后面的对象并检索该对象的字段保留的值。
我的理解是 - 1) 我在堆栈中有一个名为“myList”的引用变量,它包含堆中“MyLinkedList”类型的对象的地址。 2) 内存中与该地址对应的位置包含 12 个“节点”的另外 12 个地址。 3)每个节点(一 block 内存)保存一个对象“月”的地址。 4) 内存中Month地址对应的地方保存了(Object的)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();
}
最佳答案
首先,如果您使用通用 MyLinkedList
喜欢MyLinkedList<Month>
您将能够获得 Month
类型的对象立即从这种通用列表中脱颖而出,无需任何强制转换。
在您的特定情况下,您必须显式转换类 Object
的对象回到类Month
就像这样:Month m = (Month)obj
, 其中obj
是您从 MyLinkedList
获得的示例项目.
关于java - 如何检索存储在 LinkedList 中的对象的字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66064324/