问题
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());
}
}
The output I'm getting is,
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.
Thanks in advance!
回答1:
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
It should be like
//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);
回答2:
You're adding the same object to the list over and over again, then changing its values. This is why you're seeing the same value as well as the same memory addresses.
To get around this, instantiate different Dummy objects and place them into the list.
回答3:
The problem is that you are changing the internal state of d and adding it to LinkedList several times. You need to create new instances of Dummy.
回答4:
It is not displaying the contents of last node, but you have assigned the value as 3 to the same node(Dummy). Create a new instance of Dummy class and assign it a value and addit to the list. This will work.
来源:https://stackoverflow.com/questions/15595634/all-elements-in-linkedlist-have-same-value-as-element-added