ArrayList 的 get 方法返回指定索引处的元素。ArrayList 的索引从0开始,以 ArrayList 的长度 –1 索引结束。
ArrayList aListNumbers = new ArrayList();
aListNumbers.add(1);
aListNumbers.add(2);
aListNumbers.add(3);
/*
* To get the elements from an ArrayList, use the
* get method and specify the index.
*/
//this will print 1
System.out.println( "ArrayList element at 0 index: " + aListNumbers.get(0) );
运行后输出:
ArrayList element at 0 index: 1
注意:在获取元素之前,请检查 ArrayList 的大小。如果指定的索引超出范围,即如果索引小于 0 或大于等于 ArrayList 大小,则 get 方法将引发 IndexOutOfBoundsException 异常。
如何获取ArrayList的第一个元素?
由于 ArrayList 的索引从 0 开始,所以 ArrayList 的第一个元素的索引是 0,而不是 1。使用 get 方法并指定索引 0 可以获取 ArrayList 的第一个元素。
ArrayList aListNumbers = new ArrayList();
aListNumbers.add(1);
aListNumbers.add(2);
aListNumbers.add(3);
/*
* always make sure to check the size first to
* avoid IndexOutOfBoundsException
*/
if( aListNumbers.size() > 0 ){
/*
* To get the first element of an ArrayList, use
* the get method and specify the index as 0
*/
System.out.println( "ArrayList first element: " + aListNumbers.get(0) );
}
运行后输出:
ArrayList first element: 1
如何获取 ArrayList 的最后一个元素?
ArrayList 索引以 ArrayList 的大小 –1 索引结束。因此,ArrayList 的最后一个元素位于该索引处。
ArrayList aListNumbers = new ArrayList();
aListNumbers.add(1);
aListNumbers.add(2);
aListNumbers.add(3);
/*
* always make sure to check the size first to
* avoid IndexOutOfBoundsException
*/
if( aListNumbers.size() > 0 ){
/*
* To get the last element of an ArrayList, use
* the get method and specify the index as size - 1
*/
System.out.println( "ArrayList last element: " + aListNumbers.get( aListNumbers.size() - 1 ) );
}
运行后输出:
ArrayList last element: 3