Java 转换列表的最佳方式是什么<;字节>;列出<;整数>;

Java 转换列表的最佳方式是什么<;字节>;列出<;整数>;,java,generics,Java,Generics,哪一种是最好的转换方法?目前我正在使用下面的方法 List<Byte> bytes = new ArrayList<Byte>(); List<Object> integers = Arrays.asList(bytes.toArray()); List bytes=new ArrayList(); List integers=Arrays.asList(bytes.toArray()); 然后,整数中的每个对象都需要类型转换为整数。还有其他方法可以实现这

哪一种是最好的转换方法?目前我正在使用下面的方法

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

然后,整数中的每个对象都需要类型转换为整数。还有其他方法可以实现这一点吗?

使用标准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());
}

对于标准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());
}

如果您的项目中有谷歌的番石榴:

// assume listofBytes is of type List<Byte>
List<Integer> listOfIntegers = Ints.asList(Ints.toArray(listOfBytes));
//假设listofBytes是List类型
List-listofInteger=Ints.asList(Ints.toArray(listOfBytes));

如果您的项目中有谷歌的番石榴:

// assume listofBytes is of type List<Byte>
List<Integer> listOfIntegers = Ints.asList(Ints.toArray(listOfBytes));
//假设listofBytes是List类型
List-listofInteger=Ints.asList(Ints.toArray(listOfBytes));

您不能将
字节
类型转换为
整数
,因此您的代码可能要执行的是“序列取消装箱--转换”框。任何其他方法都会涉及显式循环或第三方LIB。您可以手动循环字节列表,强制转换对象并将它们添加到int列表
asList
将只创建列表的副本,而不会更改列表的内容。@SJuan76
asList
本身不会复制任何内容。它只是将数组的内容公开为
列表
toArray()
是进行复制的一个。您不能将
字节
键入到
整数
中,因此您的代码可能会执行“序列取消X--convert”框。任何其他方法都会涉及显式循环或第三方LIB。您可以手动循环字节列表,强制转换对象并将它们添加到int列表
asList
将只创建列表的副本,而不会更改列表的内容。@SJuan76
asList
本身不会复制任何内容。它只是将数组的内容公开为
列表
toArray()
是进行复制的那个。
用于(字节b:bytes)整数。add((int)b)
也会工作,看起来像OP当前正在做的事情。@MarkoTopolnik:你是对的,但这是假设
nulls
不是allowed@MarkoTopolnik这难道不能扔掉NPE吗?@assylias和Lukas,你们都是对的。我只是在评论OP现在正在做的事情,很明显这对他是有效的。
对于(字节b:bytes)整数。add((int)b)
也会起作用,看起来就像OP现在正在做的。@MarkoTopolnik:你说得对,然而,这是假设
nulls
不是空的allowed@MarkoTopolnik这难道不能扔掉NPE吗?@assylias和Lukas,你们都是对的。我只是在评论OP现在正在做的事情,很明显这对他是有效的。