如何将ArrayList的索引添加到相同的Arraylist Java

时间:2023-01-29 09:10:39

I want to add the an index of a 2 dimensional ArrayList to the same ArrayList. Code should be something like the following but index numbers and the same ArrayList must be involved:

我想将二维ArrayList的索引添加到同一个ArrayList中。代码应该类似于以下内容,但必须涉及索引号和相同的ArrayList:

ArrayList<String> a[0] = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> a[1] = a[0];

Of course this code won't work. Thank you in advance...

当然这段代码不起作用。先谢谢你...

1 个解决方案

#1


3  

a[i] is used to access and assign array elements.

a [i]用于访问和分配数组元素。

Assuming a is declared as :

假设a声明为:

ArrayList<ArrayList<String>> a = new ArrayList<>();

You assign the inner lists with :

您为内部列表分配:

a.set(0,new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.set(1,a.get(0));

Note that this code will work only if a's size is at least 2 (i.e. it already has values for indices 0 and 1). If a is empty, you should use :

请注意,此代码仅在a的大小至少为2时才起作用(即它已经具有索引0和1的值)。如果a为空,则应使用:

a.add (new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.add (a.get(0));

#1


3  

a[i] is used to access and assign array elements.

a [i]用于访问和分配数组元素。

Assuming a is declared as :

假设a声明为:

ArrayList<ArrayList<String>> a = new ArrayList<>();

You assign the inner lists with :

您为内部列表分配:

a.set(0,new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.set(1,a.get(0));

Note that this code will work only if a's size is at least 2 (i.e. it already has values for indices 0 and 1). If a is empty, you should use :

请注意,此代码仅在a的大小至少为2时才起作用(即它已经具有索引0和1的值)。如果a为空,则应使用:

a.add (new ArrayList<String>(Arrays.asList("A", "B", "C"));
a.add (a.get(0));