Java Generic Map<T, T> in a Generic class<T> put throws `incompatible types: T cannot be converted to T` 错误

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

我有以下 class:

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);
        }
    }
}

它在代码的 put 行抛出编译时错误 incompatible types: T cannot be converted to T。我想念什么?

您的 Prepare 方法似乎隐藏了为 class 定义的通用参数。试试这个:

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);
            }
        }
    }
}