gpt4 book ai didi

java - 为通用数组包装原语时出现未经检查的强制转换警告

转载 作者:行者123 更新时间:2023-11-29 08:32:17 25 4
gpt4 key购买 nike

我正在编写一个小的排序函数包,用于 SortableArray<T extends Comparable<T>> 类的对象。因为我希望能够对 int 这样的原始对象进行排序,我需要将基元包装在一个类对象中,在这种情况下具体来说,Integer .因此,我重载了我的构造函数以获取类型为 int 的数组。 , 将每个包装在 Integer 中,将其存储在一个数组中,temp , 然后点 GenListtemp .我添加了 (T[]) 的类型转换让 IDE 开心,但现在我有一个未经检查的类型警告。

这是我的代码:

 package sorts;

public class SortableArray<T extends Comparable<T>> {
T[] GenList;


public SortableArray(T[] theList) {
GenList = theList;
}

public SortableArray(int[] theList) {
Integer[] temp = new Integer[theList.length];
for(int i = 0; i < theList.length; i++) {
temp[i] = new Integer(theList[i]);
}
GenList = (T[]) temp; //warning here
}
}

我应该只抑制警告,还是有更安全的方法?

感谢您的回复。

最佳答案

这可能有问题的原因是如果我尝试做这样的事情:

SortableArray<String> array = new SortableArray<>(new int[] { 3, 9, 9 });

它看起来很荒谬,但它是完全合法的,当你想在其他地方使用它时会咬你一口。

您可能需要考虑的是静态工厂方法,它可能看起来像这样:

public static SortableArray<Integer> createSortableArrayFromInts(int[] theList)
{
Integer[] temp = new Integer[theList.length];
for(int i = 0; i < theList.length; i++) {
temp[i] = Integer.valueOf(theList[i]);
}
return new SortableArray<Integer>(temp);
}

关于java - 为通用数组包装原语时出现未经检查的强制转换警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46919746/

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