1. I set the values ​​for the first array.
  2. I add the first array to the second array.
  3. Clearing the first array.
  4. The array inside the array is also cleared, but why, I don’t touch it?

Example

// массив строк ArrayList<String> array1 = new ArrayList<>(); // массив с массивами строк ArrayList<ArrayList<String>> array2 = new ArrayList<>(); // добавляем в первый массив две строки array1.add("Строка_1"); array1.add("Строка_2"); // добавляем первый массив с двумя стоками во второй массив array2.add(array1); // очищаем первый массив от ранее добавленных строк array1.clear(); // проверим кол-во строк в массиве, который был добавлен в массив int size = array2.get(0).size(); // size будет равно нулю, значит массив внутри массива тоже очистился, но почему ? // как очистить array1 не затрагивая array2 ? 
  • I haven’t found the answer yet, but I have found a way to avoid it - to use ordinary arrays instead of Array List. When they are zeroed, such a disgrace is not observed. This is not a panacea, of course, but in my particular case there is no need to change the size of the array in the course of work and a regular array with a fixed length suits me. But what to do if you need ArrayList? - Vitaly Komarov

2 answers 2

Here the matter is that you operate with references to an object containing a list of strings. Those. when you created the first list of strings (array1), then you created an array in memory and now you can access it by reference in the variable array1.

After that, you created another array-list in memory and placed the variable array1 in its first cell. But, since this variable is a link, you did not create a new array in memory, but simply indicated from which memory area the second array should take values. Now you have two references to the same object in memory.

Therefore, when you clear values ​​in memory through the link array1, then the second link, array2.get(0) will show an empty array, because it displays the same memory as array1 .

If you need to create a new object in memory in the second array instead of a reference to an existing one, you need to explicitly create a new object in memory. For example:

 array2.add(new ArrayList<>(array1)); 

    Here is this line

     int size = array2.get(0).size(); 

    It means to take the contents of the first cell of the array (this is your nested array) and call size() on the object in this cell. Those. you take the size of the nested array.

     int size = array2.size(); 

    This line will return 1.

    ArrayList is an object type. When adding it to another collection, only the link is added. If you want to get a copy, you need to do this

     array2.add(new ArrayList<>(array1));