Why can't you generalize parametric classes?

Viewed 47

When you define parametric classes you can only use a fixed number of parameters.

class Container<T> {
    ...
}

However, if you want to create, say, a Map with multiple values. You must use a Map<K, List<V>> instead of Map<K, V1, V2, V3>. Why can't you define something like?

class Map<K, V, ...> {
    ...
}
1 Answers

You can, if you implement a Tuple class with 3 elements.

class Tuple3<T1, T2, T3> {
    private final T1 t1;
    private final T2 t2;
    private final T3 t3;

    // constructor, getters, ...
}

Then you can use it:

Map<K, Tuple3<V1, V2, V3>>

It is not the responsibility of Map to support multiple types of values. See separation of concerns (SoC) for more information on that topic.

Related