Reputation: 1423
Why would the code below result in the following error when trying to add to the Map?
Wrong 1st argument type. Found: 'com.test.Test.SomeEnums', required 'T'
public class Test {
public enum SomeEnums implements SomeType {
A;
public <T extends Enum<T> & SomeType> Map<T, Object> buildMap() {
Map<T, Object> map = new HashMap<>();
map.put(SomeEnums.A, new Object());
return map;
}
}
}
public interface SomeType {
}
Any ideas?
Upvotes: 1
Views: 52
Reputation: 45329
The problem is that map.put(SomeEnums.A, new Object())
is not always safe for Map<T, Object>
. Although SomeEnums
is a valid substitute for extends Enum<T> & SomeType
, it is not always the concrete type parameter.
For example, consider this second enum:
enum OtherEnum implements SomeType {
B;
}
If the same method is to be called:
Map<OtherEnum, Object> otherMap = Test.SomeEnums.A.buildMap();
This is a valid call given the signature of buildMap()
. However, the problem is that the method is adding an incorrect map key:
map.put(SomeEnums.A, new Object());
//SomeEnums.A is not always of type <T>, so this is not allowed.
The code will compile with a type cast (map.put((T) SomeEnums.A, new Object())
) - with a warning, but that's unsafe and likely not the point of the generic method.
Upvotes: 1