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

huangapple go评论75阅读模式
英文:

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&lt;T&gt; {
	private Map&lt;T, T&gt; _map;
	public MyClass(List&lt;T&gt; data) {
		_map = new HashMap&lt;T, T&gt;();
		Prepare(data);
	}
	public &lt;T&gt; void Prepare(List&lt;T&gt; 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&lt;T&gt; {
    private final Map&lt;T, T&gt; _map;
    public MyClass(final List&lt;T&gt; data) {
        _map = new HashMap&lt;T, T&gt;();
        Prepare(data);
    }
    public void Prepare(final List&lt;T&gt; data) {
        for (final T i : data) {
            if (!_map.containsKey(i)) {
                _map.put(i, i);
            }
        }
    }
}

huangapple
  • 本文由 发表于 2020年8月29日 17:33:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63645490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定