我有以下类(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);
}
}
}
它在代码中的 incompatible types: T cannot be converted to T
行抛出编译时错误 put
。我想念什么? 最佳答案
似乎您的 Prepare 方法隐藏了为该类定义的泛型参数。试试这个:
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);
}
}
}
}
关于Java Generic Map<T, T> in a Generic class<T> put 抛出 `incompatible types: T cannot be converted to T` 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63645490/