我知道有很多类似的帖子。据我了解,该错误意味着我应该更具体地使用类型。我的代码:
import java.util.*;
public class Storefront {
private LinkedList<Item> catalog = new LinkedList<Item>();
public void addItem(String id, String name, String price, String quant) {
Item it = new Item(id, name, price, quant);
catalog.add(it);
}
public Item getItem(int i) {
return (Item)catalog.get(i);
}
public int getSize() {
return catalog.size();
}
//@SuppressWarnings("unchecked")
public void sort() {
Collections.sort(catalog);
}
}
但是,我确实指定LinkedList
由类型为 Item
的对象组成。当我使用 -xlint 编译它时,我得到
warning: unchecked method invocation: method sort in class
Collections is applied to given types
Collections.sort(catalog);
required: List'<'T'>'
found: LinkedList'<'Item'>'
where T is a type-variable:
T extends Comparable'<'? super T'>' declared in method
'<'T'>'sort'<'List'<'T'>'>
据我了解,LinkedList
实现了List
,Item
实现了Comparable
.那么,"必需"和"找到"不是相同的吗?
我也在检查catalog.get(i);
是否真的是一个项目(因为有人说它可能导致问题),但它产生了同样的错误。
如果您的Item
类实现了Comparable
而不是Comparable<Item>
,则会收到此警告。确保Item
类定义如下:
class Item implements Comparable<Item> {