Monday 16 December 2019

How does Java handle ArrayList refrerences and assignments?




I mostly write in C but am using Java for this project. I want to know what Java is doing here under the hood.



ArrayList prevRow, currRow;
currRow = new ArrayList();
for(i =0; i < numRows; i++){
prevRow = currRow;
currRow.clear();
currRow.addAll(aBunchOfItems);
}



Is the prevRow = currRow line copying the list or does prevRow now point to the same list as currRow? If prevRow points to the same list as currRow, I should create a new ArrayList instead of clearing....



private ArrayList someFunction(ArrayList l){
Collections.sort(l);
return l;
}

main(){
ArrayList list = new ArrayList(Integer(3), Integer(2), Integer(1));


list = someFunction(list); //Option 1
someFunction(list); //Option 2
}


In a similar question, do Option 1 and Option 2 do the same thing in the above code?



Thanks-




Jonathan


Answer



If you come to Java from C/C++ remember this golden rule which will answer almost all these doubts: in Java a variable (except primitives) is always a reference (sort of pointer) to an object, never an object in itself.



For example



 prevRow = currRow;


is assigning a reference, so that prevRow and currRow now refer to the same object. Objects are not copied, neither in assignments, nor in argument passing (what is copied/assigned is the reference). And so on.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...