How does Java Object reference works? -


i running situation , confused. please me out. let's have code this.

myclass obj1 = null;  list<myclass> testlist = new arraylist<myclass>();  testlist.add(obj1);//after line of code, testlist have "null" @ first node  obj1 = new myclass();//after line of code, testlist still have "null"                      //at first node...                      //what want testlist's first node become new                       //myclass object 

here steps in understanding (probably incorrect...):

  1. obj1 stores pointer points nothing...
  2. testlist stores pointer points memory holds "new arraylist()"
  3. testlist add pointer of obj1 in collection.
  4. obj1 stores pointer points "new myclass()"
  5. therefore, obj1 in testlist should automatically points "new myclass()"

sorry new programming... appreciated!

here explination why testlist still have "null" @ first node after these piece of code

testlist.add(obj1);//after line of code, testlist have "null" @ first node  obj1 = new myclass();//after line of code, testlist still have "null"                      //at first node...                      //what want testlist's first node become new                       //myclass object 

step 1

myclass obj1 = null; 

this line creates space myclass reference variable (the bit holder reference value), doesn't create actual myclass object.

step 2

list<myclass> testlist = new arraylist<myclass>(); 

a list created testlist can hold objects of myclass types

step 3

testlist.add(obj1);//after line of code, testlist have "null" @ first node 

testlist first node refer null not myclass object.

step 4

obj1 = new myclass(); 

creates new myclass object on heap , assigns newly created myclass object reference variable obj1.

so how list gets updated still holding null not myclass object.

so if want make testlist's first node become new myclass object

then write lone of code after obj1 = new myclass();

testlist.set(0, obj1); 

so full code after be

myclass obj1 = null;  list<myclass> testlist = new arraylist<myclass>();  testlist.add(obj1);//after line of code, testlist have "null" @ first node  obj1 = new myclass();  testlist.set(0, obj1); 

thats problem understanding.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -