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?
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);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With