Reputation: 1915
I'm trying to design a special type of collection that may only contain elements of its own type. This collection class must also be extendable. At first glance, this seems like a simple enough task:
public class MyClass<E extends MyClass> implements Collection<E>{
//insert Collection<E> methods here...
}
However, because one of these collections may only contain elements that are instances of its class, the following shouldn't be possible:
public class MySubclass extends MyClass<MyClass>{}
What I need is a version of MyClass that essentially does the following (don't try to compile this one):
public class MyClass<E extends this.getClass()> implements Collection<E>{...}
Is it possible to implement something like this? If so, how can it be done?
Upvotes: 0
Views: 127
Reputation: 32949
I think the signature your are looking for would be something like this:
public class MyClass<E extends MyClass<E>> ...
The problem with this, and why I don't think you can enforce what you want from a declaration standpoint is that you have an infinite loop. If the collection may only contain elements of its own type, then elements can only contain elements of itself, etc, etc.
You now have an infinite loop where you may only contain Collections and at no point will you have a Collection that contains some THING.
Also, remember that at runtime type-erasure does away with all generic type. Therefore, no matter how fancy your generic declaration is at any point someone could do the following and just get a warning:
new MyClass();
That is another reason why trying to enforce this type of structure probably won't work well.
Instead you could put an appropriate check in the add
method that would provide runtime enforcement. Still have the infinite loop issue though.
EDIT
To do runtime checking, do the following:
public boolean add(E element){
if (!(element instanceof MyClass))
throw new IllegalArgumentException("Element is not an instance of MyClass");
// rest of add code here
}
Upvotes: 1