我做了一些研究,我发现在Java中,原始数据类型按值传递,而Object
和Arrays
类型通过引用传递。< / p>
我不确定我是否完全理解,当变量作为参考传递时以及何时作为值传递。
例如,如果我将对象传递给单击侦听器它可能通过引用传递,对吧? 但是,如果我将该参数的值保存在Click监听器中的实例变量中会发生什么?是否复制了数据?
我下面有示例代码(在评论中还有一些问题):
//some big class with lots of arrays
public class InfoClass{
private ArrayList<SomeObject> array1; //huge array
private ArrayList<SomeObject> array2; //huge array
//methods...
}
//listview menuitem click listener which is applied to all items
public class ListviewItemClickListener implements View.OnClickListener{
private InfoClass _info; //is this a copy of an object or a reference?
private MyArrayAdapter _adapter;
public ListviewItemClickListener(InfoClass info, MyArrayAdapter adapter){
_info = info;
_adapter = adapter;
}
@Override
public void onClick(View view) {
//do something with info class..
_adapter.notifyDataSetChanged(); //update adapter
}
}
//also:
//what about this, is this inefficient?
private class SomeClass{
public String printValueAndObjectType(Object value, Class type){
return value.toString()+" "+type.getName();
}
//example call: printValueAndObjectType("value", String.class);
//is the String.class beeing copied?
}