Reputation: 1205
community. I have the following situation. I am using java collections, lets say the List interface for example. It is a generic interface with a type parameter E for its elements. In my case I know the type of the elements that are going to be inserted, but the problem is that two types of elements are going to be inserted. Lets say I have the class A and class B and they have nothing in common. The nearest common ancestor of A and B is the Object class. The types A and B are not defined by me, so I can not change the type hierarchies. If I define my list like this:
List<A> list = new ArrayList<>();
then only elements of type A will be allowed, and if I define it like this:
List<B> list = new ArrayList<>();
then only elements of type B will be allowed. Is there any way to do a logical OR ? How to specify that I want elements of type A or type B and nothing else ? Or the java way is to make:
List<Object> list = new ArrayList<>();
and to check the type on my own when I perform any list operations ?
Upvotes: 0
Views: 114
Reputation: 3201
For your purpose, you'd need something like a union type, which Java doesn't provide. You gave the answer yourself: If you cannot modify the hierarchy, not even let A and B implement the same interface, then you'll have to use a List<Object>
and do additional typechecks yourself.
Upvotes: 2