search

Home  >  Q&A  >  body text

java - 基本类型数组如何转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[] 才能实现呢?

天蓬老师天蓬老师2822 days ago672

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 11:45:46

    As simple as it comes. java autoboxing.

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

    Latest addition

    I recently used Arrays.asList() and found that if its parameter is a basic type array, this is the error message;

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

    In other words, it treats the basic type array as a List<type[]>, that is, as a whole object.

    Another modification method is to change byte[] to Byte[], so that it can run normally. In other words, the parameter received by asList() should be an object array;
    If the parameter is an array of basic types, it will be treated as an object array with only one element (that is, the element is an array of basic types).

    reply
    0
  • Cancelreply