tags:

views:

540

answers:

4

I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious.

Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?

+3  A: 

Not really, or at least not practically.

Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A.

In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B.

That being said, there may be convulted ways that B can override certain operations to explicitly break the ability to use it in a collection or to instantiate it.

I don't think generics will solve that problem.

Uri
+2  A: 

You could use "final" in the class definition of the contained class to disallow subtyping it. I don't immediately see how you can test for this or restrict your generics to require final classes. You can use reflection to test whether the class has the final modifier set, for instance when constructing the collection, and throw if it doesn't.

If the class itself is not final, you can check every single object added to the collection to ensure that its runtime class is exactly the class the collection wants and not a subclass of it.

see http://java.sun.com/docs/books/tutorial/reflect/ for info on reflection on Java.

+3  A: 

If you create a custom collection class, you can check the class of the object on insert using reflection, and reject it if it's not of a particular exact type. Alternatively, if you have control over the class definition for the class contained in the collection, making it final will prevent subclasses from being created. (obviously this is a problem if you need subclasses for some other use)

Eric
+3  A: 

The question is: why would you want that. If you have a list containing animals, why would you want to fill that list only with the "base animal", but prevent dogs or cats being added to the list. One of the basic concepts of OO is that you use an instance of a subclass everywhere where you need in instance of the base class (Wikipedia: Liskov substitution principle). If that does not apply in your situation, something might be wrong with your class hierarchy.

Markus