基本类型数组如何转ArrayList?

Arrays.asList 可以用在对象上,但基本类型就出错了。

byte b[]=new byte[3];
b[0]=1;
b[1]=2;
b[2]=3;
ArrayList<Byte>bytes=new ArrayList<Byte>();
bytes.addAll(Arrays.asList(b));

这个提示错误

我想让 byte[] 数组 转换成 ArrayList ,这个可以实现么?
还是需要先转换成 Byte[] 数组 再转换成 byte[] 才能实现呢?

阅读 12.8k
1 个回答

怎么简单,怎么来。java自动装箱。

        for(int i=0;i<b.length;i++){
            bytes.add(b[i]);
        }

最新补充

最近用了下Arrays.asList()发现其参数如果是基本类型数组的话,是这么报错的;

Multiple markers at this line
    - The method addAll(Collection<? extends Byte>) in the type ArrayList<Byte> is not applicable for the arguments 
     (List<byte[]>)

也就是说,它把基本类型数组当成是一个List<type[]>,即当成一个整体的对象了。

另外一种改法就是把byte[]改成Byte[],这样就可以正常运行了,也就是说asList()接收的参数应该是一个对象数组;
如果参数是基本类型数组,会被当做是只有一个元素的对象数组(即该元素是一个基本类型数组)。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题