Cannot Instantiate Generic Types with Primitive Types

Consider the following parameterized type:

class Pair<K, V> {

    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // ...
}

When creating a Pair object, you cannot substitute a primitive type for the type parameter K or V:

Pair p = new Pair<>(8, 'a'); // compile-time error You can substitute only non-primitive types for the type parameters K and V:

Pair p = new Pair<>(8, 'a'); Note that the Java compiler autoboxes 8 to Integer.valueOf(8) and 'a' to Character('a'):

Pair p = new Pair<>(Integer.valueOf(8), new Character('a'));

results matching ""

    No results matching ""