如何使用ArrayList的get()方法

我是java的新手(也是OOP),我正在尝试了解类ArrayList,但我不明白如何使用get()。 我尝试在网上搜索,但找不到任何有用的东西。

这是ArrayList.get()的官方文档。

无论如何,它很简单,例如

ArrayList list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); String str = (String) list.get(0); // here you get "1" in str 

简单来说, get(int index)返回指定索引处的元素。

所以说我们有一个StringArrayList

 List names = new ArrayList(); names.add("Arthur Dent"); names.add("Marvin"); names.add("Trillian"); names.add("Ford Prefect"); 

哪个可以看作: 数组列表的直观表示 其中0,1,2和3表示ArrayList的索引。

假设我们想要检索我们将执行以下操作的名称之一: String name = names.get(1); 返回索引为1的名称。

获取索引1处的元素 所以,如果我们打印出名称System.out.println(name); 输出将是Marvin – 虽然他可能不会对我们打扰他感到高兴。

您使用List#get(int index)来获取列表中具有索引index的对象。 你这样使用它:

 List list = new ArrayList(); list.add(new ExampleClass()); list.add(new ExampleClass()); list.add(new ExampleClass()); ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2); 

这会有帮助吗?

 final List l = new ArrayList(); for (int i = 0; i < 10; i++) l.add("Number " + i); for (int i = 0; i < 10; i++) System.out.println(l.get(i)); 

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

 public Element get(int index) 

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

 package beginnersbook.com; import java.util.ArrayList; public class GetMethodExample { public static void main(String[] args) { ArrayList al = new ArrayList(); 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: pen Third element of the ArrayList: ink Sixth element of the ArrayList: books Fourth element of the ArrayList: notebook