I've found a proper way to implement the logic I was looking for, but I'm curious as to why the following doesn't work. Half an hour searching yielded no answers but it is possible I'm not wording the question properly.
What I wanted to do was limit the type parameter such that Collections would not be accepted. While I can test the parameter type, I'd rather have the IDE indicate that the Class doesn't accept a Collection as a type parameter. I'm aware that the keyword excludes doesn't exist but I hope it helps illustrate the question at hand.
public class Foo<K excludes Collection, V>
{
//TODO: Carry out Collectionist operations
}
Is there any way to do this in Java? I presume this isn't a best practice, even if it is possible, but I'd like to satiate my curiosity in an effort to expand my understanding of Generics.
Thank you for your time and consideration!
Excluding certain types is not possible. Due to the way how Java types interfaces, I could simply roll up my own Collection
that has the exact same operations, and it would not be excluded.
Just for the sake of curiosity it is a fair question, I am not aware of a way of achieving it at compile time though. You can place a runtime check in Foo
's constructor.
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