hungry91
hungry91

Reputation: 132

Generic wildcards in java. Compile error.

I have the following java code: Box<? extends Integer> i = new Box<Integer>(); i.set(10);. Why does it not compile?

Upvotes: 1

Views: 63

Answers (2)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

The following statement

Box<? extends Integer> box = new Box<Integer>(); 

means that box is covariant. And hence, you can take things out, but you can't put things in.

If you change it to the following

 Box<? super Integer> box = new Box<Integer>(); 
 box.set(10);

will work because it is contravariant now, you can put things in, but you can't take them out.

Say you have the following.

 class Box<T>{
    T t;
    void set(T t){
        this.t = t;
    }
    T get(){
        return t;
    }
 }
Box<? extends Integer> box1 = new Box<Integer>();
box1.set(10); // doesn't work
Integer i = box1.get(); // works

On the other hand

Box<? super Integer> box2 = new Box<Integer>();
box2.set(10); // works 
Integer i = box2.get(); // doesn't work

So you want to have both get/set, you can simply do this

Box<Integer> box = new Box<Integer>();
box2.set(10); // works 
Integer i = box2.get(); // works

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198023

Because a Box<? extends Integer> can be a Box<SomeSubtypeOfIntegerNotIncluding10>. You want a Box<Integer> instead.

Upvotes: 2

Related Questions