如何动态填充ArrayList?
How fill ArrayList dynamically?
如何在不确定 cell
数字的情况下填写 ArrayList
。换句话说,我怎么能有一个 ArrayList
,其中输入值和 cell
数字都是未知的。
例如我不需要下面的代码,我需要填充 ArrayList
动态:
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
我需要在 arrayList 动态(循环)中添加这些:
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
您可以使用 ArrayList.add(E)
- it will append an element to the array list and allocate the space for it if needed, no need to pre-allocate the desired space for the ArrayList
- that's the point of Dynamic Arrays.
ArrayList<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
System.out.println(arrlist);
如果你想使用循环,你可以使用 for-each loop, assuming you have your elements in some other array/Iterable:
ArrayList<Integer> arrlist = new ArrayList<Integer>();
int[] elements = {15, 22, 30, 40};
for (int x : elements) {
arrlist.add(x);
}
您可以使用命令实例化一个 ArrayList
ArrayList<Integer> list = new ArrayList <Integer> ();
然后你可以添加所有你想要的元素,如果你想知道你的ArrayList的长度,你可以使用size方法:list.size();
相当容易。
ArrayList<Integer> arrlist = new ArrayList<Integer>();
只是在创建新 ArrayList 时不要输入值。
您现在可以输入任意数量的值。
编辑:糟糕,我打字的时候已经有人回答了
我感觉你混淆了 loop 和 dynamic,它们是两个不同的东西。如果你想循环,你可以这样做:
final int[] ARRAY = {15, 22, 30, 40};
ArrayList<Integer> arrlist = new ArrayList<Integer>();
for(int i=0;i<ARRAY.length;i++) {
arrlist.add(ARRAY[i]);
}
请注意,您不必指定数组列表的初始容量。
如何在不确定 cell
数字的情况下填写 ArrayList
。换句话说,我怎么能有一个 ArrayList
,其中输入值和 cell
数字都是未知的。
例如我不需要下面的代码,我需要填充 ArrayList
动态:
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
我需要在 arrayList 动态(循环)中添加这些:
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
您可以使用 ArrayList.add(E)
- it will append an element to the array list and allocate the space for it if needed, no need to pre-allocate the desired space for the ArrayList
- that's the point of Dynamic Arrays.
ArrayList<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
System.out.println(arrlist);
如果你想使用循环,你可以使用 for-each loop, assuming you have your elements in some other array/Iterable:
ArrayList<Integer> arrlist = new ArrayList<Integer>();
int[] elements = {15, 22, 30, 40};
for (int x : elements) {
arrlist.add(x);
}
您可以使用命令实例化一个 ArrayList
ArrayList<Integer> list = new ArrayList <Integer> ();
然后你可以添加所有你想要的元素,如果你想知道你的ArrayList的长度,你可以使用size方法:list.size();
相当容易。
ArrayList<Integer> arrlist = new ArrayList<Integer>();
只是在创建新 ArrayList 时不要输入值。 您现在可以输入任意数量的值。
编辑:糟糕,我打字的时候已经有人回答了
我感觉你混淆了 loop 和 dynamic,它们是两个不同的东西。如果你想循环,你可以这样做:
final int[] ARRAY = {15, 22, 30, 40};
ArrayList<Integer> arrlist = new ArrayList<Integer>();
for(int i=0;i<ARRAY.length;i++) {
arrlist.add(ARRAY[i]);
}
请注意,您不必指定数组列表的初始容量。