泛型java运算符+未为整型int定义
我正在尝试实现一个购物车,但Integer类有一些问题。以下是代码:
public class ShoppingCart<Product, Integer> extends TreeMap<Product, Integer> {
void addToCart(Product product) {
if (this.containsKey(product)) {
Integer nrOfProds = this.get(product);
this.put(product, nrOfProds + 1); //the problem is here
} else
this.put(product, Integer.valueOf(1)); //and also here
}
....
}
Eclipse表示“运算符+未定义的整型整数int”。但我读到关于拆箱的书,我想我会没事的
没关系,我试着解决这个问题,所以我试着在nrOfProds上调用intValue()。这一次,Eclipse说“Integer类型的intValue()方法未定义”。怎么会?它是为Integer类型定义的
还有一个未定义的方法
这是怎么回事
# 1 楼答案
您已将
Integer
声明为类的类型参数,它将重写java.lang.Integer
类。声明类名时,在类名后面用尖括号括起来的值是类型参数将类声明更改为:
理想情况下,应该避免扩展
TreeMap
。而是在我的课堂上把它作为instance
字段