Conversion in Java arrays and collections

Array and List of conversion

  • List switch array: The collection method toArray ()
  • Array to a List: Arrays of using asList () method

Array is converted to a collection

Note: In the course of rotation of the collection array, to pay attention to whether the view mode of the direct return data array. When in Arrays.asList (), for example, that the array into a collection, which can not be used to modify a set of related methods, it add / remove / clear method throws an UnsupportedOperationException.

This is because Arrays.asList embodies the adapter mode, the background data is still original array. asList return object Arrays of a class is an internal, it does not modify the set of operations implemented relevant number, which is the cause of the exception is thrown.

Turn an array of collections

Turn a collection of arrays relatively simple and generally often used in the interface adapter when others

Code examples

public class Main {
    public static void main(String[] args) {

        //1.数组转换为集合
        String[] strs = new String[3];
        strs[0] = "a";
        strs[1] = "b";
        strs[2] = "c";
        List<String> stringList = Arrays.asList(strs);
        System.out.println(stringList);
        //1.1注意:直接使用add、remove、clear方法会报错
//        stringList.add("abc");
        //1.2如果想要正常的使用add等修改方法,需要重新new一个ArrayList
        List<String> trueStringList = new ArrayList<>(Arrays.asList(strs));
        trueStringList.add("abc");
        System.out.println(trueStringList);

        //2.集合转数组
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);

        //新生成的数组大小一定要大于原List的大小
        Integer[] integers = new Integer[3];
        integerList.toArray(integers);
        System.out.println(Arrays.asList(integers));
    }

}

Reproduced in: https: //www.cnblogs.com/keeya/p/11064327.html

Guess you like

Origin blog.csdn.net/weixin_33795743/article/details/93375068