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.
Related
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:
If I have an instance of an object, and within that object is a variable that holds the data of another object. If I ever update the second object will the copy of that object be updated as well or do I need to simultaneously update all copies of said object.
For example:
public class Object()
{
int x = xValue;
Object linked = saidObject;
}
public class doStuff()
{
saidObject.x++;
if(linked.equals(saidObject))
return true;
}
will this code (not compilable obviously just fill in blanks) return true?
if(linked.equals(saidObject)) will return true as the two variables do point to the same object.
In Java all variables and fields are references to an actual Object that lives somewhere in memory.
When you assign one variable to another, it's like copying the address of the object so that they both point to the same object in memory.
e.g.
Object a = new Object(); // this actually creates the Object in memory
Object b = a; // this copies the reference to Object from a to b
// At this point, a and b point to exactly the same object in memory. Therefore ...
a.equals(b); // returns true.
In fact a == b returns true too, which is a better way of comparing for this case as == compares if two variables point to the same object (they do), whereas equals() often compares by value, which is unnecessary here.
It doesn't matter if b is actually a field within a (e.g. class Obj { Obj b; }; Obj a = new Obj(); a.b = a;) and it points to the same type of object, the principle is the same: a = b means they point to same object, nothing new is created.
By doing:
Object linked = saidObject;
you are not copying the object, just creating another pointer to it, it means you have two different pointers that point to the same object.
copying or cloning an object can be useful in some cases but its not the usual case.
An object instance is itself and is distinct from every other instance.
That is, mutating an object (by reassigning a field) someplace modifies it everywhere .. as, well, it is what it is. Likewise, mutating a different object .. is, well, changing a different object.
In the code section below, I should have an ArrayList of Objs with different xValues. Instead, when I set the xValue of the Obj n on the fourth line, all Objs with the same name in the ArrayList get the xValue set to the same value.
Obj n = new Obj();
n = getObj(event.getX(), event.getY(), view.getHeight(), view.getWidth(), view);
n.setXValue(view.getWidth());
if (currentMode == AppMode.MODE.code && n != null) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
arraylist.add(n);
} // end if (event.getAction
}
What am I doing wrong? Is there a collection which will allow me to set properties of an object without messing up properties of other objects in the collection?
Java is a "pass-by-reference" language when it comes to Objects. When you put the same Object in two different collections, you're just passing a pointer to the same spot in memory to each collection, so any changes you make from one reference will affect the other reference.
If you don't desire this behavior, you have to use Object.clone() to make copies of the objects before putting them in new collections, or use some other similar copying technique.
I would guess that you wrote Obj and within Obj you have a static variable named something like XValue.
When you designate a variable as static you get one and only instance of that variable shared across all instances of that class, hence: this behavior.
Or, what torquestomp said (he's right)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java, pass-by-value, reference variables
I am a bit confused on how exactly JAVA pass by value works with object. For e.g. if I pass a object as a parameter to the method. I understand that its address is passed as value. Ok, is a duplicate of the object is kept at the original place form where the object is passed, because if I create a new reference to the object in the called API and change something in it, it doesn't get reflected in my caller API.
Below is a typical piece of code where I try to delete a tree but it's still there.
public class DeleteTree {
public static void main(String[] args) {
Node root = new Node(5);
for(int i = 0 ; i < 10 ; i++){
if(i == 5) continue;
root.insertNode(i);
}
deleteTreeNonRecursive(root);
System.out.println(root.key);
}
public static void deleteTreeNonRecursive(Node root){
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while(!q.isEmpty()){
Node temp = q.poll();
if(temp.leftChild != null)q.add(temp.leftChild);
if(temp.rightChild != null)q.add(temp.rightChild);
temp = null;
}
}
Expected O/P: nullpointer exception.
Actual O/P: 5.
In Java you always pass by value the reference to the object (which is itself allocated onto the heap). No duplication occurs because you are just passing pointers around.
In your example you are just setting temp = null but this indeed does nothing just because temp is a pointer to a Node but it's a variable local to the function, when you set it to null the original object is not touched at all just because you are just modifying the value of the reference without modifying the referenced object.
To delete the tree this is the only thing you need:
Node root = new Node(5);
for(int i = 0 ; i < 10 ; i++){
if(i == 5) continue;
root.insertNode(i);
}
root = null;
Java always uses pass by value. It's the value of the reference that is passed when it comes to object references. When you pass an object reference, it's a copy of the reference value which is passed. Using that, you can always access the object and change its properties (wherever applicable), but assigning that reference to another object or null has no consequences to the original reference in the calling method obviously.
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.