Java Generic Map in a Generic class put throws `incompatible types: T cannot be converted to T` error

Java Generic Map in a Generic class put throws `incompatible types: T cannot be converted to T` error … here is a solution to the problem.

Java Generic Map in a Generic class put throws `incompatible types: T cannot be converted to T` error

I have the following classes:

public class MyClass<T> {
    private Map<T, T> _map;
    public MyClass(List<T> data) {
        _map = new HashMap<T, T>();
        Prepare(data);
    }
    public <T> void Prepare(List<T> data) {
        for (T i : data) {
            if (!_map.containsKey(i))
                _map.put(i, i);
        }
    }
}

It throws the compile-time error incompatible types: T cannot be converted to T at the put line of code. What do I miss?

Solution

It seems that your Prepare method hides the common parameters defined for the class. Try this :

public class MyClass<T> {
    private final Map<T, T> _map;
    public MyClass(final List<T> data) {
        _map = new HashMap<T, T>();
        Prepare(data);
    }
    public void Prepare(final List<T> data) {
        for (final T i : data) {
            if (!_map.containsKey(i)) {
                _map.put(i, i);
            }
        }
    }
}

Related Problems and Solutions