gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:20:35 25 4
gpt4 key购买 nike

我有以下类(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 方法隐藏了为该类定义的通用参数。试试这个:

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 throws `incompatible types: T cannot be converted to T` error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63645490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com