原文: https://beginnersbook.com/2013/12/java-arraylist-get-method-example/
ArrayList get(int index)方法用于从列表中获取元素。我们需要在调用get方法时指定索引,并返回指定索引处的值。
public Element get(int index)
如果索引小于零或大于列表的大小(索引< 0或索引>=列表的大小),则此方法抛出IndexOutOfBoundsException。
例
在下面的例子中,我们通过使用get方法获得了一些arraylist的元素。
package beginnersbook.com;import java.util.ArrayList;public class GetMethodExample {public static void main(String[] args) {ArrayList<String> al = new ArrayList<String>();al.add("pen");al.add("pencil");al.add("ink");al.add("notebook");al.add("book");al.add("books");al.add("paper");al.add("white board");System.out.println("First element of the ArrayList: "+al.get(0));System.out.println("Third element of the ArrayList: "+al.get(2));System.out.println("Sixth element of the ArrayList: "+al.get(5));System.out.println("Fourth element of the ArrayList: "+al.get(3));}}
输出:
First element of the ArrayList: penThird element of the ArrayList: inkSixth element of the ArrayList: booksFourth element of the ArrayList: notebook
