Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generic Class Exclude Collections from Type Parameter

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!

like image 539
IdusOrtus Avatar asked Aug 18 '14 16:08

IdusOrtus


1 Answers

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.

like image 155
Alexander Gessler Avatar answered Oct 12 '22 20:10

Alexander Gessler