Links to Java. Two examples, what's the difference?

I argue with my friend.

There is:

public class Thing { private Thing s; public void foo(Thing t) { s = t; ts = this; } } 

Same as:

 public class Thing { private Thing s; public void foo(Thing t) { s = t; ss = this; } } 

I think this is the same, because in both cases s is set to t, but he does not agree with

+4
source share
4 answers

They are the same because you set them to the same link.

However, if you had two uses of new , then the links would be different, and then your friend would be right.

+6
source

Objects are passed by reference in Java. They must be the same.

+1
source

I also think the same thing, but you can check it out. just do println of two objects. bcuase, you did not implement the tostring () method, it will print the location on the heap. if the location is equal, you are right.

+1
source

Variable renaming and explicitly writing this can make it clearer:

There is:

 public class Node { private Node next; public void foo(Node t) { this.next = t; t.next = this; } } 

Same as:

 public class Node { private Node next; public void foo(Node t) { this.next = t; this.next/*==t*/.next = this; } } 
0
source

All Articles