Using an Object as argument on unbounded wildcard reference object

generics, java, unbounded-wildcard

Solution

Your example clearly explains why.

The actual type of the box is `Box<String>`. So you really don't want to be able to put something other than String instances to this box.

`Box<?>` means: "a box of some type that is unknown to the compiler". So you can get anything you want from such a box, and you'll get Object instances, but you may not store anything into the box, because the compiler can't guarantee that the object you're storing has the appropriate type:

class Box<T> {
    private T t;

    public Box(T t) {
        this.t = t;
    }

    public void put(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

Box<?> box = new Box<String>("abc");
Object o = box.get(); // no problem
box.put(new Object()); // fail

The goal of generics is to make your code type-safe. If you could add arbitrary objects to a box that is actually a `Box<String>`, you wouldn't have any type-safety anymore.

Problem

Simple class: ``` class Box<T> { private T t; public Box(T t) { this.t = t; } public void put(T t) { this.t = t; } } ``` trying to execute put() method passing an instance of Object ``` Box<?> box = new Box<String>("abc"); box.put(new Object()); ``` Compiler points out an error: ``` The method put(capture#1-of ?) in the type Box<capture#1-of ?> is not applicable for the arguments (Object) ``` Compiler in fact does not know what type to expect, but one thing is sure - it will be an Object or a subclass of it. Why is the error raised then? thank you

Original source