How does Java handle ArrayList refrerences and assignments?

拟墨画扇 提交于 2019-12-23 04:22:18

问题


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:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2777969/how-does-java-handle-arraylist-refrerences-and-assignments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!