Java ArrayList 索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4313457/
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
Java ArrayList Index
提问by Woong-Sup Jung
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?
假设我想使用 ArrayList 中的第二项。为了获得以下输出,编码是什么?
output:
输出:
banana
香蕉
采纳答案by Buhake Sindi
You have ArrayList
all wrong,
你ArrayList
都错了,
- You can't have an integer array and assign a string value.
- You cannot do a
add()
method in an array
- 您不能拥有整数数组并分配字符串值。
- 您不能
add()
在数组中执行方法
Rather do this:
而是这样做:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0
to N-1
where N
is size()
of list.
索引是从计算0
到N-1
这里N
是size()
名单。
回答by Jigar Joshi
回答by AlexR
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
就像所有类 C 语言中的数组一样。索引从 0 开始。因此,apple 为 0,banana 为 1,orange 为 2,等等。
回答by stacker
In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:
为了将字符串存储在动态数组(添加方法)中,您不能将其定义为整数数组( int[3] )。你应该这样声明:
ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
System.out.println( alist.get(1) );
回答by Ralph
Using an Array:
使用数组:
String[] fruits = new String[3]; // make a 3 element array
fruits[0]="apple";
fruits[1]="banana";
fruits[2]="orange";
System.out.println(fruits[1]); // output the second element
Using a List
使用列表
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
System.out.println(fruits.get(1));
回答by Peter Lawrey
Here is how I would write it.
这是我将如何编写它。
String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);
回答by aksarben
The big difference between primitive arrays & object-based collections (e.g., ArrayList) is that the latter can grow (or shrink) dynamically. Primitive arrays are fixed in size: Once you create them, their size doesn't change (though the contents can).
原始数组和基于对象的集合(例如,ArrayList)之间的最大区别在于后者可以动态增长(或收缩)。原始数组的大小是固定的:创建它们后,它们的大小不会改变(尽管内容可以)。