LinkedList中的所有元素与添加的元素具有相同的值 [英] All elements in LinkedList have same value as element added

查看:40
本文介绍了LinkedList中的所有元素与添加的元素具有相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Java中的链接列表类的实现.但是每次调用get方法时,我都会得到Last Node的内容.我不知道为什么.代码如下,

I'am trying to learn the implementation of Linked List class in java. But every time I call the get method, I get the contents of Last Node. I'm not able to figure out why. The code is as follow,

package learningLinkedLists;
import java.util.LinkedList;

public class LinkedLists {
public static void main(String[] args) {
    Dummy d = new Dummy(0);
    LinkedList<Dummy> ll = new LinkedList<Dummy>();


    d.SetData(1);
    d.printData();
    ll.add(d);


    d.SetData(2);
    d.printData();
    ll.add(d);

    d.SetData(3);
    ll.add(d);

    System.out.println(ll);
    System.out.println(ll.get(1).data);
    System.out.println(ll.get(0).data);
    System.out.println(ll.size());
}

}

我得到的输出是

1
2
[learningLinkedLists.Dummy@3b061299,learningLinkedLists.Dummy@3b061299,
learningLinkedLists.Dummy@3b061299]
3
3
3

我想在一个类中添加一些数据并创建该类的链接列表.

I want to add some data in a class and create linked list of that class.

提前谢谢!

推荐答案

获得相同输出的原因是因为您将相同的对象存储了两次,所以创建了两个不同的 dummyobjs ,然后将其存储

The reason why you are getting the same output is because you are storing the same object twice, create 2 different dummy objs and then store them

应该像

//Creating the first obj
Dummy d = new Dummy(0);
//Creating second ojj
Dummy d2 = new Dummy(0);
LinkedList<Dummy> ll = new LinkedList<Dummy>();


//Since d and d2 are now 2 different objects, a change to d would not have a impact on d2 and vice versa
d.SetData(1);
d2.SetData(2);
ll.add(d);
ll.add(d2);

System.out.println(ll.get(1).data);
System.out.println(ll.get(0).data);

这篇关于LinkedList中的所有元素与添加的元素具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆