gpt4 book ai didi

Java 自动装箱和拆箱

转载 作者:行者123 更新时间:2023-12-01 17:06:43 24 4
gpt4 key购买 nike

我正在尝试将整数转换并数组为列表,但是每次尝试时都会出现编译错误。

   List<Integer> integers = toList(draw.getToto6From49().getFirstRound());

// getFirstRound() returns int[] ;

这是我的 to toList 方法

public class ArraysUtil {


public static <T> List<T> toList(T[] ts) {
List<T> ts1 = new ArrayList<>();
Collections.addAll(ts1, ts);
return ts1;
}
}

java: com.totoplay.util.ArraysUtil 类中的 toList 方法无法应用于给定类型;

  required: T[]
found: int[]
reason: inferred type does not conform to declared bound(s)
inferred: int
bound(s): java.lang.Object

最佳答案

是的,基本上你不能这样做。您期望能够使用 int 类型参数调用 toList,而 Java 不允许将基元用作类型参数。您基本上需要为每个要处理的原语使用不同的方法,例如

public static List<Integer> toList(int[] ts) {
List<Integer> list = new ArrayList<>(ts.length);
for (int i in ts) {
list.add(i);
}
}

至少,Java 7 及之前的版本是这样。在 Java 8 中稍微简单一些:

int[] array = { 1, 2, 3 };
IntStream stream = Arrays.stream(array);
List<Integer> list = stream.boxed().collect(Collectors.toList());

关于Java 自动装箱和拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com