2012-08-16 57 views
1

这是最好的方法目前我使用类似下面什么是转换列表<Byte>列出<Integer>

List<Byte> bytes = new ArrayList<Byte>(); 
List<Object> integers = Arrays.asList(bytes.toArray()); 

然后需要被强制转换为整数整数里面的每个对象转换的最佳途径。有什么其他方式可以实现这一目标吗?

+1

你不能为'Integer'类型'Byte'所以你的代码可能是什么确实是序列unbox - 转换框。任何其他方式来执行此操作仍然会涉及显式循环或第三方库。 – 2012-08-16 11:26:43

+0

您可以手动遍历字节列表,投射对象并将它们添加到int列表 – Paranaix 2012-08-16 11:27:25

+2

'asList'只会创建列表的副本,而不会更改列表的内容。 – SJuan76 2012-08-16 11:28:41

回答

4

与标准的JDK,这里是如何做到这一点

List<Byte> bytes = new ArrayList<Byte>(); 
// [...] Fill the bytes list somehow 

List<Integer> integers = new ArrayList<Integer>(); 
for (Byte b : bytes) { 
    integers.add(b == null ? null : b.intValue()); 
} 

如果你确定,你没有任何nullbytes

for (byte b : bytes) { 
    integers.add((int) b); 
} 
+0

'for(byte b:bytes)integers.add((int)b)'也可以工作,看起来像OP当前正在做的事情。 – 2012-08-16 11:27:59

+0

@MarkoTopolnik:你说的对,但假设不允许有'nulls' – 2012-08-16 11:28:41

+0

@MarkoTopolnik能不能抛出NPE? – assylias 2012-08-16 11:28:46

0

如果谷歌的番石榴可用你的项目:

// assume listofBytes is of type List<Byte> 
List<Integer> listOfIntegers = Ints.asList(Ints.toArray(listOfBytes));