简体   繁体   中英

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
  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

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.

//Add my data to my list type2
for (String s : things) {
    list1.add(s);
}

This is a for-each loop. 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. It executes once for each item in the things array.

//Add my data to my list type3
list1.addAll(Arrays.asList(things));

In this method, Arrays class is used. asList method of Arrays class returns a list backed by a specified array, in your case, that array is things . Each item in list returned by asList method then gets added to list1 using addAll method.

Basically, they all do the same thing , ie add all the items of things array in list1 arraylist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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