学习如何使用索引位置从ArrayList中获取元素。我们将使用ArrayList.get()方法从ArrayList中获取指定索引位置的对象。
// 快速指南
ArrayList<String> places = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e", "f"));
String firstElement = list.get(0); //a
String sixthElement = list.get(5); //f
1. ArrayList get() 方法
ArrayList.get(int index)方法返回列表中指定位置’index’处的元素。
1.1. 语法
public Object get( int index );
1.2. 方法参数
index – 要返回的元素的索引。有效的索引始终在0(包括)到ArrayList大小(不包括)之间。 例如,如果ArrayList包含10个对象,那么有效的索引参数将在0到9之间(包括0和9)。

程序员导航
优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站
1.3. 返回值
get()方法返回指定索引位置处的对象的引用。
1.4. IndexOutOfBoundsException
无效的索引参数将导致IndexOutOfBoundsException错误。
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at com.howtodoinjava.example.ArrayListExample.main(ArrayListExample.java:12)
2. ArrayList get() 示例
Java程序演示如何通过其索引位置从ArrayList中获取对象。在本示例中,我们希望获取存储在索引位置0和1处的对象。
ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles", "dough"));
String firstName = list.get(0); //alex
String secondName = list.get(1); //brian
以上就是Java ArrayList get() 获取索引位置的元素方法详解的全部内容。

AI 工具导航
优网导航旗下AI工具导航,精选全球千款优质 AI 工具集
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



