tags:

views:

107

answers:

3

Hey all-

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<Integer> prevRow, currRow;
currRow = new ArrayList<Integer>();
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<Integer> someFunction(ArrayList<Integer> l){
    Collections.sort(l);
    return l;
}

main(){
    ArrayList<Integer> list = new ArrayList<Integer>(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

+1  A: 
  1. Think of any instance created with the "new" keyword as a pointer. prevRow now points to the same thing currRow does. The only value types in Java are the primitives (byte, char, int, long, float, double). Everything else is an Object. Arrays of primitives fall into the Object category (created with "new").
  2. Yes (if you fix the return type/return statement so it will compile ;)).
Yann Ramin
+4  A: 

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.

leonbloy
+1  A: 

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..

It is now a reference to the same list. So clearing it will nuke your prevList. Insead do currRow = new ArrayList<Integer>()

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

Yes they do. You are passing a reference to your list, and changing it. So both work. Option 2 is a little more clear on what you are doing and I prefer it stylewise, but both work.

Remember, Java is always pass by VALUE.. but for non primitive (any class that starts with a capital generally..), you are passing the value of the memory address, not the value of the stuff inside. For primative (int, float), then you just pass the value.

bwawok