一、Arrays.asList()
public class ListDemo {
public static void main(String[] args) {
String[] split = "abc,bcd,cde,def".split(",");
List<String> list = Arrays.asList(split);
//list.add("ggg");
list.remove("abc");
System.out.println(list);
}
}
Convert the array to a list through Arrays.asList(), the list can only be checked and modified, and the following exceptions will be thrown when adding and deleting operations:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractCollection.remove(AbstractCollection.java:293)
at com.lzw.demo6.ListDemo.main(ListDemo.java:12)
We can analyze the source code:
This method returns the Arrays class inside a static inner classes java.util.Arrays.ArrayList,
useless rewrite add
, remove
method, and therefore will throw an exception when you call the add method.
Second, through the tool class Collections.addAll()
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListDemo2 {
public static void main(String[] args) {
String[] split = "abc,bcd,cde,def".split(",");
List< String> list = new ArrayList<String>(split.length);
Collections.addAll(list,split);
list.add("ggg");
list.remove("abc");
System.out.println(list);
}
}
[bcd, cde, def, ggg]
This method is the most efficient. It is converted by Collections.addAll(arrayList, strArray), a List of the same length is created according to the length of the array, and then the elements in the array are converted to binary by the Collections.addAll() method, and then added to List. It can be used when the amount of list data is large, which can increase efficiency.
Third, java.util.ArrayList
the constructor used
package com.lzw.demo6;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListDemo3 {
public static void main(String[] args) {
String[] split = "abc,bcd,cde,def".split(",");
List<String> list = new ArrayList<>(Arrays.asList(split));
list.add("ggg");
list.remove("abc");
System.out.println(list);
}
}
This method can add, delete, and check when the amount of data is small, but it is not efficient when the amount of data is large.