ArrayList<Integer> inter=new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> ar = new ArrayList<>(); inter.add(2); inter.add(3); ar.add(inter); inter.add(44); inter.add(62); 

Why, when I add elements to the inter sheet, already after I added 2 и 3 to the two-dimensional sheet itself, it automatically continues to add 44 и 62 although below, I didn’t indicate it anywhere? when displaying System.out.println(ar); the result will be 2 3 44 62

  • inter is an object reference. Those. essentially the address of the memory location where the list is located. And in ar you get links. Accordingly, the object remains the same, t.ch. changing it, you will see the change, referring to it by any link that points to it. You need to copy the list. - Kirill Malyshev
  • @ Kirill Malyshev if I need for example 2 and 3 to be stored in the 0 index of the ar sheet, and 44 and 62 in 1 index, what do I need to do? If ar is an array of links, if I understood correctly - Ark
  • @Ark, you need to create another ArrayList <Integer> object, add (44 and 62) with add (), and add it after adding the inter object. - Alex Tremasov 2:57 pm
  • @GinTasan did this already, just the problem is that all the necessary numbers are stored current in one sheet of inter, the only thing that came up, wrote below to your answer, but I do not know how correct it is - Ark

1 answer 1

You create an ArrayList inter object and add 2 elements 2 and 3 to it, then add an inter object to ar, i.e. the reference of this object, then there is an addition of 44 and 62, and ar already through the link can work with the memory space where the inter object refers to. Therefore, ar has access to elements 44 and 62

UPD:

 ArrayList<Integer> inter=new ArrayList<Integer>(); ArrayList<Integer> inter_one=new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> ar = new ArrayList<>(); inter.add(2); inter.add(3); inter_one.add(44); inter_one.add(62); ar.add(inter); ar.add(inter_one); 

UPD: Option, which is proposed to implement in the comments

  • Is there a more "correct" way than this?: inter.add (2); inter.add (3); inter.add (35); ar.get (0) .add (inter.get (0)); ar.get (0) .add (inter.get (1)); ar.get (0) .add (inter.get (2)); or have to turn every time element by element? - Ark
  • Basically, in such variants cycles are created, with the help of which there is an opportunity to reduce the code and improve performance - Alex Tremasov
  • It seems the only option is only cycles, thanks! - Ark
  • Still looking at what you need to implement, I advise you to look at the main collections and work with them, you can make completely different options, good luck) - Alex Tremasov