Java中关于Arrays用法的一个易错点

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&lt;String&gt; 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);
        }
    }
}

在这里插入图片描述
问题就解决了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值