Hame
Hame

Reputation: 544

java operator + not defined for type(s) Integer, int

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.

Theres also a problem with with Integer.valueOf(1). Its undefined method, again.

What is wrong with this?

Upvotes: 2

Views: 1849

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213321

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.

Upvotes: 14

Related Questions