使用Arrays.asList()时遇到的坑

若数组中元素的类型是封装类型或String时,使用Arrays.asList()能顺利的将数组转换成List<T>

若数组中元素的类型是基础数据类型时,使用Arrays.asList()只能将其转换成List<T[ ]>

String[] strs = {"Jack", "Blue", "Color"};
List<String> strings = Arrays.asList(strs);

//char类型
char[] chars = str.toCharArray();
List<char[]> chars1 = Arrays.asList(chars);

//int类型
int[] ints = new int[]{};
List<int[]> ints1 = Arrays.asList(ints);

//Integer类型
Integer[] integers = new Integer[]{};
List<Integer> integerList = Arrays.asList(integers);

这是因为 Arrays的asList()方法的入参是一个泛型类型,但基本数据类型并不是类Class,又由于char[ ]或int[ ]是一种类型,因此会返回List<char[ ]>或List<Int[ ]>。

public static <T> List<T> asList(T... a) {
	return new ArrayList<>(a);
}

有人可能会觉得我说"char[ ]或int[ ]是一种类型"解释的牵强附会,其实这并非是我信口开河。请看下面的代码:

System.out.println(int[].class);   //输出class [I

System.out.println(char[].class); //输出class [C

System.out.println(int.class); //输出int

System.out.println(Employee.class); //class com.mmr.learn.jdk8.entity.Employee   (这是我自己定义的类型)

System.out.println(Integer.class); //输出 class java.lang.Integer

打印“类型.class”的输出结果时会返回"class 路径",而int.class返回的是"int"。这是因为,根据jdk1.1规定,Java提供了9个预先定义好的Class对象(此Class与我们定义的Employee,Interger, Long,Arrays有着本质的区别),分别代表了8个基本数据类型和1个void(无返回值类型),它们由JVM虚拟机创建。根据jdk1.1的源码显示 : int.class与Integer.TYPE等价

/**
 * The {@code Class} instance representing the primitive type
 * {@code int}.
 *
 * @since   JDK1.1
 */
@SuppressWarnings("unchecked")
public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

但与Integer.class截然不同。 int.class只不过是一个Class<Integer>类型的引用,而Integer.class是一个实实在在的类

发布了45 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/miaomiao19971215/article/details/90523962