public class Main {
public static void main(String[] args) {
byte[] a=new byte[3];
List<Byte> c=new ArrayList<Byte>();
c.addAll(Arrays.asList(a));
//The method addAll(Collection<? extends Byte>) in the type List<Byte>
//is not applicable for the arguments (List<byte[]>)
Collections.addAll(c, a);
//The method addAll(Collection<? super T>, T...) in the type Collections
//is not applicable for the arguments (List<Byte>, byte[])
}
}
最后两行给出编译错误。
要解决这个问题,首先我读了这个 Create ArrayList from array 讨论。我尝试这个解决方案,但它不起作用。 这里 Converting array to list in Java 是解释为什么它不起作用,但不是解决方案。
“源数组是字节的原始数组,而不是 Byte 对象”是正确的,我希望存在更漂亮的解决方案,然后迭代并转换每个元素。
最佳答案
你的数组必须是Byte数组,而不是byte数组。 addAll 需要匹配的对象集合。
换句话说: 字节[] a=新字节[3];
或者,如果您的源数组是原始字节数组,而不是 Byte 对象,那么您必须循环遍历它们并一次添加一个:
for( byte toInsert: a ){
c.add((Byte)a);// Probably don't need the cast, but included for clarity
}
关于java - 如何从基本类型元素数组创建 ArrayList (ArrayList<T>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600097/