3

I am implementing singly linked list in Java, and I have a problem. In addition and removal of nodes, many people use temporary node like this:

public Object removeFirst() {
   Node temp = head;
   head = temp.next;
   Object returnData = temp.data;
   temp = null;
   size--;
   return returnData;
}

Why is this temp node necessary? At first glance, I think all I have to do in order to remove first element is to change second element into head node.

So my question is that in java, what does object= object mean? Do 2 objects become exactly same inheriting every fields and methods?

Ravindra babu
  • 45,953
  • 8
  • 231
  • 206
JUNTAE
  • 63
  • 4
  • 3
    I suspect you'd benefit from reading https://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference/32010236#32010236 – Jon Skeet Feb 05 '18 at 11:11
  • Thank you! analogies there helped a lot to get a sesne – JUNTAE Feb 05 '18 at 11:16
  • 2
    Please edit the title so it makes more sence. I can't even begin to guess what `class = class?` supposed to mean. – M. Prokhorov Feb 05 '18 at 11:20

2 Answers2

6

temp is not needed. It is used to obtain the data of the removed Node after the head variable is no longer referencing that Node, but that can be done without it:

public Object removeFirst() 
{
    Object returnData = head.data;
    head = head.next;
    size--;
    return returnData;
}
Eran
  • 374,785
  • 51
  • 663
  • 734
2

what does object= object mean?

A class provides the blueprint for objects; you create an object from a class.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type

Assume that you have create new object head

When you copy one object to another object, then second reference is created to the object.

Node temp = head;

If you make second object (reference) as null,this object is still accessible with first reference (head).

Do 2 objects become exactly same inheriting every fields and methods?

Yes since only reference is different but object is same.

You can find more details in oracle documentation page

  1. When you did not create object ( instantiate class):

enter image description here

  1. When you create an object with new operator:

enter image description here

  1. When you assign object to another object:

enter image description here

Ravindra babu
  • 45,953
  • 8
  • 231
  • 206