Java, what is happening internally when you do object = object? - java

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?

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

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
When you did not create object ( instantiate class):
When you create an object with new operator:
When you assign object to another object:

Related

Creating a variable of type class in Java [duplicate]

This question already has answers here:
Is it okay for a class to have a field of its own type
(4 answers)
having a field with the same class inside a class
(4 answers)
How can a class have a member of its own type, isn't this infinite recursion?
(7 answers)
Closed 3 years ago.
In the code there is Node next in class Node. I am not able to understand what exactly it is doing. Is it creating a object named next. And is there value getting stored in it when nodeA.next = nodeB is used.
I am trying to learn LinkedList but i am not able to get what is exactly happening.
class Node{
int data ;
Node next;
Node(int data){
this.data = data ;
}
}
Node nodeA = new Node(6);
Node nodeB = new Node(3);
Node nodeC = new Node(2);
nodeA.next = nodeB;
nodeB.next = nodeC;
Lets split the code up and explain the parts:
class Node {
}
This is the syntax to create a new class. The class is named "Node".
int data;
This defines an instance variable. Each instance of type Node should have a variable called data of type int.
Node next;
This defines another instance variable. It is called next and it holds a reference to a Node.
Node(int data){
this.data = data ;
}
This is a so called constructor. It takes an argument data and then it is stored inside the instance variable data. (The instance variable is referenced with "this.", because the parameter data is hiding the instance variable with the same name.)
That was the class itself. So now we look at the use of it (This does not make sense outside a class / function. Such code should be part of a function e.g. inside a main function):
Node nodeA = new Node(6);
Node nodeB = new Node(3);
Node nodeC = new Node(2);
This creates 3 instances of the class node and it is storing it inside nodeA, nodeB and nodeC variables.
nodeA.next = nodeB;
nodeB.next = nodeC;
Here, we set the next instance variable of nodeA and nodeB and assign the nodeB and nodeC.
And this gives us a so called linked list. An element of the list can point to another element (or when there is no element reference in it, then it is null by default.
Did this help understanding the code? If not: Where exactly do you have problems understanding the code?

Can I define an object as equal to another one in Java?

In Java programs, is it right to set an object equal to another one? To be more specific, I'm studying binary trees and I noticed in the following code:
public Node find(int key)
{
Node current = root;
while(current.iData != key)
{
if(key < current.iData)
{
current = current.leftChild;
} else {
//...
}
}
}
that both Node current = root; and current - current.leftChild; are setting an object equal to another one. Is this right?
setting an object equal to another one. Is this right?
No, that's not right.
What's actually happening is, you're changing the reference of one variable to another object.
So:
Node current = root; // "current" will point at the same object as `root`.
and
current = current.leftChild; // "current" will point at the same object as `leftChild`.
note -
When assigning primitive types with = is a completely different behaviour when assigning reference types with =.
First of all, you need to need a basic concept in Java: Java does manipulate objects by reference, and all object variables are references.
So when you have Object o1 and Object o2, in fact o1 and o2 are just references to memory spaces that hold the object not the object itself.
When you have o1 == o2 , you are comparing the two references not the objects themselves but if you want to compare them you need to override the equals() method.
Now, let's talk about your case:
Node current = root; this means that current and root are referring to the same object (the same location in memory). So there is only one object and two references.

Is there a difference in functionality when you use an intermediate variable during assignment?

I'm having trouble understanding what makes method A different from method B.
public class ListNode {
public String data;
public ListNode next;
public ListNode(String data, ListNode next) {
this.data = data;
this.next = next;
}
}
public void A(ListNode list, String name) {
ListNode asdf = new ListNode("hello", list);
list = asdf;
}
public void B(ListNode list, String name) {
list = new ListNode("hello", list);
}
No difference (functionally speaking).
Note that re-binding a method parameter is confusing because parameters in Java are passed by value, so when the method ends, list will be the same value as before the method call, no matter if you re-bind inside the method. This means your newly created ListNode object will have no strong reference and will be eventually garbage-collected.
For example:
final ListNode a = new ListNode("pre-call", list);
A(a, "Some name");
System.out.println(a.data); // Here it will print "pre-call" and not "hello"
Also it is usually considered a bad practice to re-bind parameters (kind of same as reusing variables). To avoid such mistakes I always declare method parameters as final.
The only difference is the readability of the two methods. Rest both the methods are doing the same thing
In method A the first reference is asdf for newly created ListNode object. this ' list = asdf' makes list as another reference to same ListNode object. Thus in method A there are two references for same object.
And the method B also does the same thing ie creates a new ListNode but this time using list as only reference.
Both methods achieve same thing but method A creates two references and assigns object to list indirectly while B on other hand directly uses list as a reference.

What does "this" refer to exactly in this code?

public CharList(CharList l)
{
// Whatever method your CharList provides to get the
// first node in the list goes here
CharNode pt = l.head();
// create a new head node for *this* list
CharNode newNode = new CharNode();
this.head = newNode;
// Go through old list, copy data, create new nodes
// for this list.
while(pt != null)
{
newNode.setCharacter(pt.getCharacter());
pt = pt.getNext();
if (pt != null)
{
newNode.setNext(new CharNode());
newNode = newNode.getNext();
}
}
}
I thought that this is used to refer to the Object A as in "A.addElement(car);", but in this case I don't know what this refers to... And I don't see the point in doing: this.head = newNode; since this.head is never used again.
this refers to the current instance of CharList, and this.head refers to the instance field head. You can discard this keyword to access instance fields if there are no local variables with the same name.
The docs explain what this is:
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
The keyword this refers to the current instance of CharList. It is useful for referring to variables that may share the same at class level, otherwise it can be omitted.
Here, no local variable head does not appear in the constructor of CharList, so can be written as:
head = newNode;
this.head is never used again.
Since head is a member variable of the class, the value set in the constructor will be used in other methods of the class.
Possible duplicate of What is the meaning of "this" in Java?, but anyway:
It's a reference to the specific instance of the object you're working with. So, if I have (going to write this in C#, sorry):
public class MyObject
{
public MyObject(string AString)
{
MyString = AString;
}
private string MyString;
public string WhatsMyStringCalled()
{
return this.MyString;
}
}
If I were to construct an instance of MyObject, I would expect WhatsMyStringCalled to return the MyString property associated with that particular instance.

Dynamic Implementation of Linked List

class Nodetype
{
int info;
Nodetype next;
Nodetype(int i)
{
info=i;
next=null;
}
}
My textbook has this code to create Linked List dynamically.
The question is, when the programs is executed line-by line, it defines variable 'info' as type 'int' & then variable 'next' as Nodetype.
What is actually happening here?
does it mean that variable 'next' will contain -
Constructor 'Nodetype'
int info
Nodetype "next" where "next" will again have all 1,2,3 & then 3 will again have 1,2,3...and so on....till infinity?
I'm really irritated because I'm unable to understand how it works, can someone easily explain this?
Your code follows very well the definition of list: a list is null or an element followed by a list.
The "element", in your case, is defined by an int value, and the "followed by" part is the next variable; in Java variables (when they are not literals, as int values are) are actually pointers, so while they are not initialized they don't store any valid value and they don't point to any memory area (i.e. their value is null), so while the next variable is kept as-is your element is not followed by any other. To dynamically add elements to your list you need a pointer to the last element you added, otherwise you would not be able to find them again:
int i = 0;
Nodetype head = new Nodetype(i++);
Nodetype last = new Nodetype(i++);
head.next = last;
while (i<5) {
Nodetype temp = new Nodetype(i++);
last.next = temp;
last = temp;
}
while(head) {
System.out.println(head.info);
head = head.next;
}
Notice how, with the last few lines, you lose the head pointer and you have no way to get back the starting point of your list.. Keep that in mind when working with lists ;)
At first variable next doesn't point to any object(it points to null). At some time you will make it point to another node with next = new NodeType(number). The idea is that you use composition - you have one instance of class which has a reference to another instance. It is like nodeA points to nodeB, nodeB points to nodeC. Here you have three instances and the first instance has a reference to the second instance and the second instance has a reference to the third instance. The third instance is the last one and its next instance points to null.
the field next is a reference to an object of type Nodetype. at first it will point to nothing - since it is instantiated to null. when you assign a value to it, it will point to that value only, nothing will continue infinitely unless you create a cycle within the list.
You created class NodeType and inside of the class you defined object of that class. So that object (in your example next) will have int info variable NodeType next object and constructor.
It will contain Null, as the variable is not initialized to any value.
Nodetype is your class that defines the data a node instance will contain as well as the reference to the next node in the linked list. That reference to the next node will be an object of type Nodetype. Nothing too difficult here, this is the classic implementation of a Linked List.
You might want to check out this great linked list resource from Stanford.
The way this works is that the list is made up of single elements, each of which only has a pointer to the one that comes after it:
Nodetype next;
The information each element within the list actually holds is this:
int info;
You can think of a list like a "chain": it's not really a single object, but a compound object of a number of links. From each link, you can only see the next link (or, in case of linked lists that have references in both directions: the next and the previous link), so in order to have all elements available, you will have to keep the reference to the first element in the "chain".
Note: List objects are single objects that have a reference to the first link of the "chain".
next is a reference to another Nodetype instance. If next == null it means the current element is the last one in the list.
Let's see an example:
Nodetype node = new Nodetype(0); // i = 0, next = null
Nodetype anotherNode = new Nodetype(1); // i = 1, next = null
node.next = anotherNode; // now the first node has a ref to the second
#include<stdio.h>
#include<stdlib.h>
void print_list(int *arr,int *size,int *capacity)
{
printf("capacity = %d; size = %d; elements = ",*capacity,*size);
for(int i=0;i<(*size);i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int * push_back(int *arr,int data,int *size,int *capacity)
{
int *b;
if(*size == *capacity){
*capacity = 2*(*capacity);
b = (int *)malloc(sizeof(int)*(*capacity));
for(int i=0;i<(*size);i++){
b[i]= arr[i];
}
b[*size]=data;
*size=*size+1;
print_list(b,size,capacity);
return b;
}
arr[*size]=data;
*size=*size+1;
print_list(arr,size,capacity);
return arr;
}
int main()
{
int size=0;
int n;
int x;
int *arr;
arr = (int *) malloc(sizeof(int));
int capacity=1;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&x);
arr=push_back(arr,x,&size,&capacity);
}
}
its working.

Categories