java中数组与集合相互转化

版权声明:菜鸟的蜕变 https://blog.csdn.net/IdealSpring/article/details/81475811

一、数组转化成集合

        使用Arrays.asList(T... a)方法,将数组转换成List集合。

        代码实例:    

package cn.ccut;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        Integer[] array = new Integer[]{1, 2, 3};

        List<Integer> list = Arrays.asList(array);
        list.forEach(student -> System.out.println(student));
    }
}

二、将集合转换成指定类型的数组

        使用ArrayList(其他集合类均可)集合的toArray(T[] a)方法。

        示例代码:

package cn.ccut;

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();

        list.add(new Student("1号"));
        list.add(new Student("2号"));

        Student[] students = list.toArray(new Student[0]);
        for (Student s : students) {
            System.out.println(s);
        }
    }
}

ArrayList的toArray(T[] a)方法详解

        方法中所传入的参数主要作用是指定该方法的返回数组的类型,传入数组有两种情况:

                1.参数数组的长度小于集合长度时,直接将集合转换成参数的数据类型返回。

                2.参数数组的长度大于集合长度时,将集合转换成参数的数据类型并且返回的数组长度等于参数数组的长度(使用null填充)。

在ArrayList中源码如下:

@SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

总结:

        我的需求是将list集合转换成数组,数组长度等于原集合的长度,故我传入的参数为new Student[0]。

猜你喜欢

转载自blog.csdn.net/IdealSpring/article/details/81475811