[英]Questions about ArrayList
I need to use an ArrayList
, but I am not sure how to do some of these things that would be possible with a normal array. 我需要使用ArrayList
,但是我不确定如何执行普通数组可能的某些操作。
1) This: 1):
int[][] example1 = new int[10][20];
(An array with two arguments (10, 20)) is possible with normal arrays, but how to do it with an ArrayList
.) (具有两个参数(10,20)的数组对于普通数组是可行的,但如何使用ArrayList
做到这一点。)
2) How to increase the value of an int on the list by 1, like this: 2)如何将列表中的int值增加1,如下所示:
example2[3][4] ++;
ArrayList
is dynamically growable list backed by array. ArrayList
是由数组支持的可动态增长的列表。
List<List<Integer>> list = new ArrayList<List<>>(10);
you can get an element of list by List#get
. 您可以通过List#get
list的元素。
List<Integer> innerList = list.get(3);
Integer integer = innerList.get(4);
Update value by List#set
- 通过List#set
更新值-
list.get(3).set(4,list.get(3).get(4)++);
NOTE : Integer
class is immutable. 注意: Integer
类是不可变的。
To mimic a multidimensional array using collections you would use: 要使用集合来模拟多维数组,可以使用:
List<List<Integer>> list = new ArrayList<>(); //Java 7
List<List<Integer>> list = new ArrayList<List<Integer>>(); //Pre Java 7
So lets say we create a List<List<Integer>>
where the outer List
contains 10 List<Integer>
and the inner list contains 10 Integer
s. 假设我们创建一个List<List<Integer>>
,其中外部List
包含10个List<Integer>
,内部List包含10个Integer
。 To set the fifth element on the fourth list: 要在第四个列表上设置第五个元素:
public static void main(String[] args) {
List<List<Integer>> outer = new ArrayList<List<Integer>>();
for(int x = 0; x < 10; x++){
List<Integer> inner = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
outer.add(inner);
}
//Remember that Integer is immutable
outer.get(3).set(4, new Integer(outer.get(3).get(4)) + 1);
}
int[][] example1 = new int[10][20];
ArrayList<ArrayList<Integer>> ex = new ArrayList<ArrayList<Integer>>();
example2[3][4] ++;
int val = (a.get(0).get(0)) + 1;
The equivalent of your declaration with an ArrayList
is: 带有ArrayList
的声明等效于:
List<List<Integer>> example1 = new ArrayList<>();
You have to use Integer
because Java Collections do not support primitive types. 您必须使用Integer
因为Java集合不支持基本类型。 Check out this page of the Oracle docs for more information on Autoboxing and Unboxing. 请查看Oracle文档的此页面,以获取有关自动装箱和拆箱的更多信息。
Since an ArrayList
can grow dynamically, you don't need to give a size. 由于ArrayList
可以动态增长,因此您无需提供大小。 If you want it to have an initial size, you can pass that as an argument to the constructor. 如果您希望它具有初始大小,则可以将其作为参数传递给构造函数。
You can get elements from an ArrayList
(or any Class implementing the List
interface) by using the get()
method with the index of the element as an argument. 您可以通过使用get()
方法(以元素的索引作为参数get()
从ArrayList
(或实现List
接口的任何Class)中get()
元素。
Using example.get()
on example1
will give you an object of the type List
. 在example1
上使用example.get()
将为您提供List
类型的对象。 You can then use get()
again to get an Integer
. 然后,您可以再次使用get()
获得一个Integer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.