Hungry
Hungry

Reputation: 1665

Collection allowing multiple, predefined types

As the question states, is it possible to define a collection which allows only a set of predefined, and potentially unrelated types (I.e. which do not extend from a common object). This sort of thing:

List<Foo|Bar> list = new ArrayList<Foo|Bar>();
list.add(new Foo());//Allow
list.add(new Bar());//Allow
list.add(new Baz());//Disallow

Since I have never seen this done before, I am assuming it is probably not possible. If not, then is there a good reason for why not?

One solution I guess would be to have each necessary class inherit an empty interface, then set the type of the list to this interface. Would this be considered 'normal' practice?

Upvotes: 0

Views: 52

Answers (1)

Eran
Eran

Reputation: 393841

It's not possible (assuming Foo and Bar have no common super class other than Object and no common interface).

The reason:

Suppose it was possible :

List<Foo|Bar> list = new ArrayList<Foo|Bar>();
list.add(new Foo());//Allow
list.add(new Bar());//Allow

Now, what type would list.get(0) return?

Neither of these two lines can pass compilation, since list.get(0) can't be of both types:

Foo foo = list.get(0);
Bar bar = list.get(0);

This means the only thing that can compile would be :

Object obj = list.get(0);

and that has no advantage over using the raw List type.

Upvotes: 3

Related Questions