It's been a while since I touched generics in Java, I have this:
Map<List<MyGenericType>, Set<List<MyGenericType>>> x = new HashMap<>();
In truth, MyGenericType requires a generic parameter, since it is defined like this:
public class MyGenericType<X> {}
I declared x with pre-emptive type-erasure of MyGenericType because I didn't want to make an empty marker interface just for the sake of grouping things. Will this, for the sake of having a collection, work in my favor or will I have to make a marker interface to make this possible?
(EDIT) That is:
public interface SomeCommonInterface {...}MyGenericType implements SomeCommonInterface ...Map<List<SomeCommonInterface>, Set<List<SomeCommonInterface>>> x = new HashMap<>();Recall that Integer as well as Double both extend Number and in turn, Number extends Object.
A List<Number> is in no way usable as a List<Integer> and vice versa. List<Number> x = new ArrayList<Integer> does not compile. This is called 'invariance', and it is 'correct', because if it did compile, you could add doubles to a list of integers which is obviously not right. It tends to throw people off, though, which is why I mention it. If you want covariance or contravariance, you must opt into this: List<? extends Number> list = new ArrayList<Integer>(); does compile. But then list.add(5); won't, because if it did, you would again be able to add doubles to a list of integers and that wouldn't be right.
Once you entirely omit generics on a thing, all type checking on generics is right out the door, and you don't want that. Can you 'get away with it'? Well, uh, the compiler will toss a bunch of warnings in your face and you turn off quite a bit of type checking. If you mean with 'get away with it': "Does it compile"? Yes, it does. If you mean: "Would this code pass any reasonable java coder's code review"? No, it won't.
Simple solution: What's wrong with using MyGenericType<?> here?
NB: Keys in maps should be immutable; list is not. Using it is therefore quite a bad plan; what is that supposed to represent?
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