Is there a Union in Java Generics?

Nope. You have a couple of alternatives, though:

  • You can use a List < Object > and stash whatever you like; or

  • You can use a List < Class-with-2-members > and put your data in one of those class members.

EDIT: Example.

class UnionHolder {
  public String stringValue;
  public int intValue;
}

List < UnionHolder > myList 
...

Of course you'll need a bit of additional code to figure out which kind of data to pull out of the UnionHolder object you just got out of your list. One possibility would be to have a 3rd member which has different values depending on which it is, or you could, say, have a member function like

public boolean isItAString() { return (this.stringValue != null }

Short answer? No. You can (of course) have a List of Objects, but then you can put anything in it, not just String or Integer objects.

You could create a list of container objects, and that container object would contain either an Integer or String (perhaps via generics). A little more hassle.

public class Contained<T> {
   T getContained();
}

and implement Contained<Integer> and Contained<String>.

Of course, the real question is why you want to do this? I would expect a collection to contain objects of the same type, and then I can iterate through and perform actions on these objects without worrying what they are. Perhaps your object hierarchy needs further thought?

Tags:

Java

Generics