I am trying to implement a shopping cart and I have some problems with the Integer class. This is the code:
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 says "operator + undefined for type(s) Integer, int". But I read about unboxing, and I thought I would be ok.
Never mind, I tried to work this around, so I tried calling intValue() on nrOfProds. This time, Eclipse said "method intValue() is undefined for type Integer". How come? It is defined for type Integer.
There s also a problem with with Integer.valueOf(1). It
s also a problem with with Integer.valueOf(1). It
s undefined method, again.
What is wrong with this?
You have declared Integer
as type parameter of your class, which overrides the java.lang.Integer
class. The values you give after the class name in angular brackets while declaring it are type parameters.
Change the class declaration to:
public class ShoppingCart extends TreeMap<Product, Integer>
Ideally, you should avoid extending the TreeMap
. Rather have it as an instance
field in my class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.