[英]Cannot use “this” to reference an object to create a linked list
我有一个包含AClass类型属性的类(称为AClass)。 我试图用它来创建一个整数的链表。 但是,每当我给AClass中的数据一个值时,它都会用该值替换所有链接类中的数据。
public class AClass {
public AClass rest;
public int data;
public AClass (int tData) {
data=tData;
rest=null;
}
public void add(int item) {
rest=this; //This is what is causing the problem
data=item;
}
}
这就是我正在测试的东西。 我的输出应该是5,6,5,但我得到了5,6,6。
public class Test {
public static void main(String[] args) {
AClass aTest=new AClass(5); //Creates a list with on element.
System.out.println(aTest.data); //Print that element for verification
aTest.add(6);
System.out.println(aTest.data); //Print the end element
System.out.println(aTest.rest.data); //Print the next element, which should be 5
}
}
我似乎无法弄清楚我在做什么错。
让我们考虑一下链接列表是什么,以及代码的作用。
链表是一组由一系列指针链接在一起的节点。 根据您所描述的预期行为,您需要一个这样构建的链表。
public class Test {
public static void main(String[] args) {
AClass aTest=new AClass(5); // Data: aTest ==> (5) ==> null
System.out.println(aTest.data); // Prints 5.
aTest.add(6); // Data: aTest ==> (6) ==> (5) ==> null
System.out.println(aTest.data); // Prints 6
System.out.println(aTest.rest.data); // Prints 5
}
}
但是,根据您的实现,您实际上不会创建第二个节点-您只有原始节点,并且损坏了链表。
public class Test {
public static void main(String[] args) {
AClass aTest=new AClass(5); // Data: aTest ==> (5) ==> null
System.out.println(aTest.data); // Prints 5.
aTest.add(6); // Data: aTest ==> (6) ==> (6) ==> (6) ==> forever
System.out.println(aTest.data); // Prints 6
System.out.println(aTest.rest.data); // Prints 6
}
}
因此,您需要add
以创建一个新节点:
rest=this;
将下一个指针设置为当前对象,从而创建一个正好是一个元素的循环链接列表。 您需要创建一个新元素。 您还面临着一个有趣的问题,即假设要向哪个方向添加项目。可以将其添加到列表的前面,也可以添加到列表的后面,但是请注意,添加到前面意味着要更改指向前面的指针。 您可以很容易地实现addFront
和addBack
:
public AClass addFront(int item) {
AClass node = new AClass(item);
node.rest = this;
return node;
}
public void addBack(int item) {
// Find the end of the list
AClass temp = this;
while (temp.rest != null) {
temp = temp.rest;
}
temp.rest = new AClass(item);
}
话虽如此,请考虑使用内置的链接列表: http : //docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html 。
public class AClass {
public AClass rest;
public int data;
public AClass (int tData) {
data=tData;
}
/**
* Insert in front.
* @param item data to be inserted.
*/
public void add(int item) {
// Make a copy of this:
AClass copy = new AClass(data);
copy.rest = rest;
// Overwrite this object:
rest = copy;
data = item;
}
}
aTest.rest.data
您正在使用引用变量aTest访问类型为AClass的 其余实例变量。 其余与aTest具有相同的引用。 当说aTest.rest.data时,这是另一种说aTest.data的方式 , data的当前值为6 。 这就是为什么要获得5、6、6作为输出的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.