Conversion between Java List and Array

A .Array turned List

1. Implementation: java in the array to a list using Arrays.asList (T ... a) method.

public class Array2List {
public static void main(String[] args){
List<String> listA=Arrays.asList("dog","cat","cow");
String[] strs={"dog","cat","cow"};
List<String> listB= Arrays.asList(strs);
System.out.println(listA);
System.out.println(listB);
}
}
2.注意事项

Object 1) Arrays.asList () method returns the type Arrays internal operation of the list is still reflected in the original array, so this list length is fixed, does not support the add, remove operation;

2) Since the method of the generic parameter asList acceptable basic types can not be used, only using the following method:

public class Array2List {
public static void main(String[] args){
int[] a={1,2,3,4,5};
List<Integer> list=new ArrayList<>();
for(int i:a){
list.add(i);
}
System.out.println(list);
}
}
二.List转为Array

1. Implementation: Use list.toArray ()

public class Array2List {
public static void main(String[] args){
List<String> list=new ArrayList<>();
list.add("dog");
list.add("cat");
list.add("cow");
String[] animals=list.toArray(new String[0]);
for(String animal:animals){
System.out.println(animal);
}
}
}
 

 

 
---------------------

Guess you like

Origin www.cnblogs.com/hyhy904/p/11161446.html