0

I have created a Node class which takes the a value (int) in the constructor. It also can store another Node as 'next'. I have found out that when I create a Node like this:

public void methodSignature(int value) {Node node = new Node(value);}

in a method, and then on another call of the method creates the exact same object if the input is the same. Why is this? What can I do to avoid it? It's cauing issues with my program.

Kristina
  • 97
  • 1
  • 8
  • How did you determine that it creates "the exact same object"? Did you just print out the hashcode or something similar? – OH GOD SPIDERS Oct 14 '21 at 09:54
  • Is it a singleton? What does the Node constructor look like? What does System.out.println(new Node(value) == new Node(value)) display? You can edit your question to include more information. – Sourabh Bhat Oct 14 '21 at 09:59
  • I tested like this: `if(node == (anotherNode.next)) {System.out.println("true")}`. To be sure: `==` means that they have the same memory address, right? – Kristina Oct 14 '21 at 10:00
  • 1
    `System.out.println(new Node(1) == new Node(1));` displays false... Hm, I suppose I might have misunderstood what is wrong with my program. But that is helpful. Thank you. – Kristina Oct 14 '21 at 10:05
  • Well, that just sounds like `anotherNode.next` actually references "the" `node` you are talking about. – maloomeister Oct 14 '21 at 10:06
  • @Kristina Yes, if you tested with `==` then this means they are indeed the exacts same object. The thing is however I strong suspect that wherever `node` and `anotherNode.next` got their values from is not 2 different calls of `new Node(value)`, but one and the same that you assign to those 2 different variables. using the `new` keyord in java will always create a new object in memory and I would be very surprised if you had a special JVM version where that isn't the case. – OH GOD SPIDERS Oct 14 '21 at 10:06
  • It means that the `next` is same as `node`. Not that same object is created every time. Probably you have written `anotherNode.next = node` somewhere in your code – Sourabh Bhat Oct 14 '21 at 10:09
  • @SourabhBhat I totally had written anotherNode.next = node. – Kristina Oct 18 '21 at 08:36
  • Thank you, everyone, for helping out. I was eventually able to solve it. – Kristina Oct 18 '21 at 08:36

0 Answers0