简体   繁体   English

这三种方法有什么区别?

[英]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 它们都做相同的事情,但是复杂度不同

  1. First one is most native and uses index 第一个是最原生的并且使用索引
  2. Second one uses string iterator in foreach loop style 第二个在foreach循环样式中使用字符串迭代器
  3. Third one uses eachmethod styled addition 第三个使用每种方法样式的加法

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM