[英]What is the difference between these three methods?
String[] things = {"hello", "plastic", "eggs"};
List<String> list1 = new ArrayList<String>();
//Add datas to my list type1
for (int i = 0; i < things.length; i++) {
list1.add(things[i]);
}
//Add my data to my list type2
for (String s : things) {
list1.add(s);
}
//Add my data to my list type3
list1.addAll(Arrays.asList(things));
They all do the same thing but vary in complexity 它们都做相同的事情,但是复杂度不同
Point to note is that advanced method like 3rd one may not be supported in lower versions of java like android_sdk<20 需要注意的是,较低版本的Java(如android_sdk <20)可能不支持第3种高级方法
for (int i = 0; i < things.length; i++) {
list1.add(things[i]);
}
This is a for loop
which executes as long as the condition (i < things.length)
holds true. 这是一个
for loop
,只要条件(i < things.length)
true,就执行该for loop
。
//Add my data to my list type2
for (String s : things) {
list1.add(s);
}
This is a for-each
loop. 这是一个
for-each
循环。 It is different from for loop
in a way that you don't need to specify the condition until which you want to execute the loop. 它与
for loop
不同之处在于,您无需指定条件即可执行循环。 It executes once for each item in the things
array. 它对
things
数组中的每个项目执行一次。
//Add my data to my list type3
list1.addAll(Arrays.asList(things));
In this method, Arrays
class is used. 在此方法中,使用了
Arrays
类。 asList
method of Arrays
class returns a list backed by a specified array, in your case, that array is things
. asList
的方法Arrays
类返回列表支持由指定的数组,你的情况,该数组things
。 Each item in list returned by asList
method then gets added to list1
using addAll
method. 然后,使用
addAll
方法将由asList
方法返回的列表中的每个项目添加到list1
。
Basically, they all do the same thing , ie add all the items of things
array in list1
arraylist. 基本上, 它们都做相同的事情 ,即在
list1
arraylist中添加things
数组的所有项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.