在我最近的类作业中,我们一直在使用泛型,我收到了此警告:
Note: Selector.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
据我了解,这是由于未指定集合中对象的类型而导致的。我目前正在使用 int 进行测试,但该程序应该允许对任何类型对象进行排序。我认为我不想将我的集合指定为 int,因此我的集合当前为 T 类型。但我的指示明确指出我的程序不应生成任何警告。这是我的方法之一:
我现在拥有的:
else {
T[] a = new T[c.size()];
c.toArray(T[] a);
T min = a[0];
for (int i = 0; i < a.size(); i++) {
if (comp.compare(min, a[i]) > 0) {
min = a[i];
}
}
return min;
}
我得到了什么:
Testing.java:48: error: generic array creation
T[] a = c.toArray(new T[c.size()]);
最佳答案
要删除您应该使用的通知
Collection.toArray(T[] a)
而不是
Collection.toArray()
Collection.toArray() 返回一个对象数组,因此您始终需要进行转换。
此外,调用 toArray 的成本很高,因为必须创建新数组,因此您应该考虑将其存储到变量中并重复使用。
不幸的是,不可能创建泛型类型的数组,因此我认为您应该删除 toArray 并在集合上使用迭代器,例如:
Iterator<T> iterator = c.iterator();
T min = iterator.next(); //you already checked that there has to be first element
while (iterator.hasNext()) {
T element = iterator.next();
if (comp.compare(min, element) > 0) {
min = element;
}
}
return min;
关于java - 未经检查或不安全的操作作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14656902/