我知道有很多类似的帖子.据我所知,错误意味着我应该对类型更具体.我的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我确实指定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'>'>
Run Code Online (Sandbox Code Playgroud)
据我所知,LinkedList实现List和Item实现Comparable.那么,不是"必需"和"找到"相同吗?
此外,我正在检查是否catalog.get(i);实际上是一个项目(因为,有人说它可能导致了问题),但它产生了同样的错误.
如果您的Item类实现Comparable而不是,则会收到此警告Comparable<Item>.确保您的Item类定义如下:
class Item implements Comparable<Item> {
Run Code Online (Sandbox Code Playgroud)