I have an ArrayList of type my model, which conatins 3 items, that is the ArrayList size is 3.
ArrayList<Model> mModels; // mModels.size() = 3
I have to copy this ArrayList in to another ArrayList, so for that I have created another ArrayList of same type as follows.
ArrayList<Model> localModels = new ArrayList<>(mModels.size());
next step is to copy data from member variable to local variable, since I dont want to copy the reference of member variable I have used Collections.copy()
Collections.copy(localModels,mModels);
but I am getting ArrayOutOfBoundException by telling destination size should be greater than source size. so I have logged both variable size. then for the member I got the size as 3 and for the localVariable logged the size as 0.
UPDATE
and I have tried copiying member ArrayList to local one. but it copies only reference. is there any way to copy the data instead of reference ?
I have tried these methods
//1
for(Model model: mModels){
localModels.add(model);
}
//2
for(Model model: mModels){
localModels.add((Model)model.clone());
}
//3
Collections.copy(localModels, mModels);
//4
localModels = (ArrayList<Model>)mModels.clone();
//5
localModels = new ArrayList<>(mModels);
so my questions are
1- how can I copy (value change should not reflect) value from one ArrayList to another ?
2- why java/android always copiying the reference
3- how to intialize ArrayList with predefined size (already answered)