英文:
Java Generic Map<T, T> in a Generic class<T> put throws `incompatible types: T cannot be converted to T` error
问题
在代码的put
行上,它会抛出编译时错误,错误消息是incompatible types: T cannot be converted to T
。我漏掉了什么?
英文:
I have the following 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);
}
}
}
It throws compile-time error incompatible types: T cannot be converted to T
at the put
line in the code. What do I miss?
答案1
得分: 3
似乎你的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);
}
}
}
}
英文:
Seems like your Prepare method hides the generic parameter defined for the class. Try this instead:
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);
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论