4

i'm having an argue with my friend.

Is:

public class Thing
{
    private Thing 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

user978945
  • 41
  • 1

4 Answers4

6

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.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
1

Objects pass by reference in Java. These should both be the same.

Kirk
  • 16,182
  • 20
  • 80
  • 112
  • 1
    For the purposes of this discussion you are correct. Though some may disagree about Java passing by reference. It merely passes copies of object references as values or so says one line of thinking. Interesting post here, [Is Java pass by reference?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference). – New Guy Oct 04 '11 at 17:42
1

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.

stdcall
  • 27,613
  • 18
  • 81
  • 125
0

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;
    }
}
user786653
  • 29,780
  • 4
  • 43
  • 53