0

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!

SureshS
  • 589
  • 8
  • 23

4 Answers4

8

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);
Akash
  • 4,956
  • 11
  • 42
  • 70
  • I didn't get you. I have changed the content of 'd' and then I'am storing it in list. – SureshS Mar 24 '13 at 05:56
  • 1
    Yes, since object values are stored as references, the same reference is being stored twice. Causing 2 elements in the link list to point to the same object – Akash Mar 24 '13 at 05:59
  • Thanks! I got where I was going wrong. – SureshS Mar 24 '13 at 06:02
4

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
4

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.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
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.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38