Java 如何使用 get() 方法访问 arrayList 中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9652812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would use a get() method to access an element in an arrayList?
提问by user1254044
This is my code I have so far but I don't know how to access an element in the Array myList?
这是我到目前为止的代码,但我不知道如何访问数组 myList 中的元素?
And is the inex of an array list start at 0 or 1? I have just found out about array lists and i need a few pointers and some help
数组列表的 inex 是从 0 还是 1 开始?我刚刚发现了数组列表,我需要一些指针和一些帮助
ArrayList<String> myList = new ArrayList<String>();
myList.add("hello");
myList.add("5");
myList.add("3");
myList.add("8");
int totalElements = myList.size();
System.out.println(totalElements);
private String[] myList;
public String getList() {
return this.myList[0];
回答by donnior
In java, array's index is start from 0.
在java中,数组的索引从0开始。
To access the nth element in one list, you can call list.get(n)
.
要访问一个列表中的第 n 个元素,您可以调用list.get(n)
.
回答by juergen d
String a = myList.get(0); //a = "hello"
String b = myList.get(1); //b = "5"
回答by noMAD
All you have to do is:
您所要做的就是:
myList.get(Index);
This would return you the type of Object
you used while creating the ArrayList
. In your case it will return a String
. Hence, what you can do is:
这将返回您Object
在创建ArrayList
. 在您的情况下,它将返回一个String
. 因此,您可以做的是:
String firstElement = myList.get(0); //This would return "Hello"
This also shows that ArrayList
indices start with 0
这也表明ArrayList
索引从 0 开始