Reputation: 1027
I have an Activity with an ArrayList and also i have extended a View,Activity and View are in seperated classes.
public class activity extends Activity{
private ArrayList<customObject> ar = new ArrayList<customObject>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawview = new DrawView(this,ar);
setContentView(drawview);//more code
}}
As you see i pass to the constructor of the draview the ArrayList of my activity so i can handle the objects of ArrayList has.i gave the same names of ArrayList in both classes.(if that matters...)
class DrawView extends View {
private ArrayList<customObject> ar;
public DrawView(Context context,ArrayList<customObject> a) {
super(context);
this.ar=a;
}
//more code
}
And now a very very very weird thing....As far as i know java is call by value,so i can't actually pass memory segments of where i store my arraylist...so the only values should the drawview could see are the ones that i have passed on the constructor....BUT when i add values in the ArrayList of the Activity the values are also an din the aaraylist of the view!!!! Could this be happening??why this is happening...i'am very confused...
Upvotes: 0
Views: 565
Reputation: 87513
In Java, parameters are indeed passed-by-value, but all non-primitives in Java are references. So when you pass a reference, the reference (memory address) is passed by value and the net effect is that the object or array pointed to by the reference has been passed by value.
In other words, your array was effectively passed call-by-reference - its the same array.
Edit: from the comments:
The variable ar
references (points to) an array. The ar
was passed to the DrawView
constructor. The variable ar
was passed by value, so the value of ar
(the memory address of the array) was copied into constructor parameter a
. So now ar
and a
point to the same array, i.e. effectively passing the array by reference.
Upvotes: 2