Java – ArrayList is not initialized with a predefined size

ArrayList is not initialized with a predefined size… here is a solution to the problem.

ArrayList is not initialized with a predefined size

I have an ArrayList of my model type with 3 items, i.e. the ArrayList size is 3.

ArrayList<Model> mModels;  mModels.size() = 3

I

had to copy this ArrayList to another ArrayList, so I created another ArrayList of the same type as shown below.

ArrayList<Model> localModels = new ArrayList<>(mModels.size());

The next step is to copy the data from the member variable to the local variable, because I don’t want to copy the reference to the member variable I use with Collections.copy().

Collections.copy(localModels,mModels);

But I get ArrayOutOfBoundException by telling the target size should be greater than the source size. So I recorded two variable sizes. Then for members, I get a size of 3, and for localVariable, I record the size as 0.

Update

And I’m trying to copy the member ArrayList to the local member. But it only copies the reference. Is there any way to copy data instead of references?

I’ve tried all of 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 question is

1- How do I copy values from one ArrayList (value changes should not reflect) to another?

2- Why does java/android always copy references

3- How to initialize the ArrayList with a predefined size (answered).

Solution

ArrayList<Model> localModels = new ArrayList<>(mModels.size());

Create an ArrayList with an initial capacity equal to mModels.size() (3 in your example), but it contains 0 elements.

You must add elements to the ArrayList so that it has a positive number of elements.

If you want your localModels ArrayList to contain the same elements as mModels, you can initialize it using the following method:

ArrayList<Model> localModels = new ArrayList<>(mModels); 

However, this will give you a shallow copy of the original ArrayList.

Related Problems and Solutions