Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

1. Array to list

  • Arrays.asList
/ / array List String [] str1 = new String [] {" a ", "b", "c"}; List<String> strList = Arrays.asList(str1); System.out.println(strList); Integer[] int1 = new Integer[]{1,2,3}; List<Integer> intList = Arrays.asList(int1); System.out.println(intList);Copy the code

But what’s wrong with adding and deleting data now?

Throw UnsupportedOperationException abnormal, why will appear this problem?

String[] str1 = new String[]{"a","b","c"};
List<String> strList = Arrays.asList(str1);
### System.out.println(strList); //输出了[a, b, c]

List<String> list = new ArrayList<>();
list.addAll(strList);
list.add("e");
System.out.println(list);  //输出了[a, b, c, e]
Copy the code
  • The arrays.aslist (str1) method calls the following method: The Arrays method calls a private static class that doesn’t add methods so it throws exceptions.
SafeVarargs public static <T> List<T> asList(T... a) { return new Arrays.ArrayList(a); }Copy the code

  • And our new ArrayList his catalog is Java. Util. The ArrayList and above is Java. Util. Arrays. The ArrayList, we in the ArrayList he and those methods, he will include creating new method

So if you want to go from an array to a list without adding or deleting you can use the asList method and if you want to do that you need to do something with the array that you’re rolling out, As I will be above the Java. Util. Arrays. The ArrayList to Java. Util. ArrayList can operate

  • Of course, another operation is to use a Java8 stream
List<String> lsitStr = Arrays.stream(new String[]{"aa", "bb", "cc"}).collect(Collectors.toList()); lsitStr.add("dd"); System.out.println(lsitStr); List<Integer> listInt = array.stream (new Integer[]{1,2,3}).collect(Collectors. ToList ()); listInt.add(4); System.out.println(listInt);Copy the code

2. Turn the list array

There are also two methods used here: the first is to use list.toarray directly and the second is to use the stream

//List to ArrayList< Integer> List = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Integer[] str1 = list.toArray(list.toArray(new Integer[list.size()])); System.out.println(str1); int[] str2 = list.stream().mapToInt(Integer::intValue).toArray(); System.out.println(str1);Copy the code