Array. asList: Convert array to list, Array. aslistlist
String s [] = {"aa", "bb", "cc"}; List <String> sList = Arrays. asList (s); for (String str: sList) {// can traverse each element System. out. println (str);} System. out. println (sList. size (); // 3 System. out. println ("--"); int I [] = {11, 22, 33}; List intList = Arrays. asList (I); // There is an Integer array type Object in intList. The entire array is stored as an element for (Object o: intList) {// System. out. println (o. toString ();} System. out. println ("--"); Integer ob [] = {11, 22, 33}; List <Integer> objList = Arrays. asList (ob); // each element in the array is used as an element in the list for (int a: objList) {System. out. println (a);} System. out. println ("--"); // objList. remove (0); // asList () returns the private ultimate ArrayList type in arrays. It has the set, get, and contains methods, but there is no method to add or delete elements, therefore, if the size is fixed, an error is reported. // objList. add (0); // an error is reported because no add method exists in the implementation class of the list returned by asList.
Output result:
- Aa
- Bb
- Cc
- 3
- -----------
- [I @ 287efdd8
- -----------
- 11
- 22
- 33
- -----------
If you want to obtain a new normal list based on the array, you can add them one by one in a loop, or you can use either of the following two methods:
ArrayList <Integer> copyArrays = new ArrayList <Integer> (Arrays. asList (ob); // you can obtain a new list, which can be added and copyArrays is removed. add (222); // normal, no error Collections. addAll (new ArrayList <Integer> (5), ob); // or create an empty list and use Collections to convert the array. addAll
In addition, we will discuss Collections. addAll and list. addAll.
List <Integer> list1 = new ArrayList <Integer> () {add (0); add (-1 );}}; list <Integer> list2 = new ArrayList <Integer> (Arrays. asList (2, 4,-9); list1.addAll (list2); System. out. println (list1); list2.set (0, 100000); System. out. println (list1); // Copy System in depth. out. println (); // functional display Collections. addAll (list2, 34, 67, 78); System. out. println (list2); list2.addAll (Arrays. asList (34, 67, 78); System. out. println (list2); System. out. println ();
Result:
[0,-1, 2, 4,-9]
[0,-1, 2, 4,-9]
[100000, 4,-9, 34, 67, 78]
[100000, 4,-9, 34, 67, 78, 34, 67, 78]