Jonny Stewart
Jonny Stewart

Reputation: 161

Java, two objects, object1 = object2 = class/type ... don't understand

I have two instance variables, head and tail. In the code there's a line:

head = tail = new Node<E>();

Does this mean that there are two instances, head and tail, of class Node? I'm quite confused here.

Upvotes: 4

Views: 3580

Answers (8)

Pankaj Kakulate
Pankaj Kakulate

Reputation: 1

object1=object2 ;

Here Object1 one refrence to other means simply object2 is copied all addresses to object1 reference

Simply object2 is copied into object1

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

The 2 references head and tail are both assigned to the same single instance of Node.

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

It simply means:

tail = new Node<E>();
head = tail;

So there are 2 references (head and tail) pointing to the same Node<E> instance.

Upvotes: 13

Matheus
Matheus

Reputation: 291

Only one object is created, head and tail both references the same object.

Upvotes: 1

chad
chad

Reputation: 7519

No certainly not.

Here's what's happening in this code, in sequence.

  1. 'new' is used to create an instance, aka an object, of the Node class
  2. a reference to this instance is stored in the tail reference
  3. a reference to this instance is stored in the head reference.

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405735

No, there's only one instance of Node<E>created, but both head and tail refer to it, so you have two reference variables that point to the same object.

Upvotes: 3

durron597
durron597

Reputation: 32323

This means there are TWO references to ONE Object Node.

The line tail = new Node<E>(); actually returns a value (in this case an object reference) equal to the assigned value.

Upvotes: 4

kosa
kosa

Reputation: 66637

Only one instance of Node. Both head and tail references pointing to same instance.

Upvotes: 2

Related Questions