原文: https://beginnersbook.com/2013/12/java-arraylist-get-method-example/

ArrayList get(int index)方法用于从列表中获取元素。我们需要在调用get方法时指定索引,并返回指定索引处的值。

public Element get(int index)

如果索引小于零或大于列表的大小(索引< 0或索引>=列表的大小),则此方法抛出IndexOutOfBoundsException

在下面的例子中,我们通过使用get方法获得了一些arraylist的元素。

  1. package beginnersbook.com;
  2. import java.util.ArrayList;
  3. public class GetMethodExample {
  4. public static void main(String[] args) {
  5. ArrayList<String> al = new ArrayList<String>();
  6. al.add("pen");
  7. al.add("pencil");
  8. al.add("ink");
  9. al.add("notebook");
  10. al.add("book");
  11. al.add("books");
  12. al.add("paper");
  13. al.add("white board");
  14. System.out.println("First element of the ArrayList: "+al.get(0));
  15. System.out.println("Third element of the ArrayList: "+al.get(2));
  16. System.out.println("Sixth element of the ArrayList: "+al.get(5));
  17. System.out.println("Fourth element of the ArrayList: "+al.get(3));
  18. }
  19. }

输出:

  1. First element of the ArrayList: pen
  2. Third element of the ArrayList: ink
  3. Sixth element of the ArrayList: books
  4. Fourth element of the ArrayList: notebook

参考:

ArrayList.get(int))