2012-04-21 99 views
7

我是新来的java(& OOP太),我想了解类ArrayList 但我不明白如何使用get()。我试着在网上搜索,但找不到任何有用的东西。如何使用ArrayList的get()方法

+0

你对这种方法完全不了解吗? – Mat 2012-04-21 14:08:24

+0

我不明白如何使用它 – madU 2012-04-21 14:23:35

+0

Object x = myarray.get(1); – 2018-02-08 21:21:01

回答

19

这里是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 
+1

如果您使用的是Java 1.5或更高版本,建议您使用泛型。 – EpicPandaForce 2014-07-07 20:24:16

1

请问这帮助?

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

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

List<ExampleClass> list = new ArrayList<ExampleClass>(); 
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); 
+0

List list = new ArrayList (); 请使用<>东西的含义是什么? – madU 2012-04-21 14:16:38

+0

这是列表的一般类型,请看这里:http://docs.oracle.com/javase/tutorial/java/generics/index.html – MByD 2012-04-21 14:19:10