References in Java. Two examples, whats the difference?
i'm having an argue with my friend.
Is:
public class Thing
{
private Thing 开发者_JAVA技巧s;
public void foo(Thing t)
{
s = t;
t.s = this;
}
}
The same as:
public class Thing
{
private Thing s;
public void foo(Thing t)
{
s = t;
s.s = this;
}
}
I think its the same since s is set to t in both cases, but he disagrees
They're the same since you're setting them to the same reference.
However, if you had two uses of new
then the references would be different, and then your friend would be correct.
Objects pass by reference in Java. These should both be the same.
I also think it's the same, but you can surely check it. just do a println of the two object. bcuase you haven't implemented the tostring() method, it will print the location in the heap. if the location is equal, you are the right one.
Variable renaming and explicitly writing this
might make it clearer:
Is:
public class Node
{
private Node next;
public void foo(Node t)
{
this.next = t;
t.next = this;
}
}
The same as:
public class Node
{
private Node next;
public void foo(Node t)
{
this.next = t;
this.next/*==t*/.next = this;
}
}
精彩评论