如何处理Java的ArrayList的refrerences和任务? [英] How does Java handle ArrayList refrerences and assignments?
问题描述
我主要是用C编写,但我使用Java这个项目。我想知道什么是Java的引擎盖下在这里干什么。
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);
}
是prevRow = currRow行复制列表还是prevRow现在指向同一个列表,currRow?如果prevRow指向同一列表作为currRow,我应该创建一个新的ArrayList,而不是结算的....
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
}
在一个类似的问题,做方案1和方案2在上面做code是一回事吗?
In a similar question, do Option 1 and Option 2 do the same thing in the above code?
谢谢 -
乔纳森
推荐答案
如果你来的Java从C / C ++记住这条黄金法则可以回答几乎所有的这些疑惑:Java中的一个变量(除了基本类型)是的始终参考(排序的指针)一个对象,本身从来不是一个对象。
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.
例如
prevRow = currRow;
被分配一个参考,使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.
这篇关于如何处理Java的ArrayList的refrerences和任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!