Java中Arrays用法的一个易错点
Arrays是Java提供给开放人员对数组进行操作的类,他里面有很多对数组的操作方法,如sort(),toString(),asList()等,今天要说的易错点就是asList()方法,这个方法可以将一个数组转换为List。
当我们对使用保存包装类的数组进行转换时会发现没有任何问题
但是如果数组保存的是基本类型的话,就会发现不正确了。如下。
public class Test01 {
public static void main(String[] args) {
int arr[]=new int[]{1,2,3,4,5,6,7,8,9,10};
List<int[]> ints = Arrays.asList(arr);
for (int[] anInt : ints) {
System.out.println(anInt);
}
}
}
我们会发现List并没有转换arr数组成功,而是产生了一个保存元素为arr数组的List集合,它的输出结果如下。
是数组在内存中的地址值。
为什么会出现这种情况捏,我们可以(ctrl+A)点进源码看一下。
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
可以看到传入了一个T类型的参数,这是什么东西捏,上面有一行关于它的解释———数组存储对象的class,那我们就明白了class属性是基本数据类型所没有的,但我们可以使用它们的包装类来处理。
public class Test02 {
public static void main(String[] args) {
Integer arr[]=new Integer[]{1,2,3,4,5,6,7,8,9,10};
List<Integer> integers = Arrays.asList(arr);
for (Integer integer : integers) {
System.out.println(integer);
}
}
}
问题就解决了