user978945
user978945

Reputation: 41

References in Java. Two examples, whats the difference?

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

Upvotes: 4

Views: 123

Answers (4)

user786653
user786653

Reputation: 30450

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;
    }
}

Upvotes: 0

stdcall
stdcall

Reputation: 28860

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.

Upvotes: 1

Kirk
Kirk

Reputation: 16245

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

Upvotes: 1

Platinum Azure
Platinum Azure

Reputation: 46183

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.

Upvotes: 6

Related Questions