Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Union in Java Generics?

Tags:

java

generics

Can I contain two different types in a collection? For example, can I have List< String U Integer > ?

like image 992
unj2 Avatar asked Nov 08 '09 19:11

unj2


People also ask

Are there unions in Java?

Since the Java programming language does not provide the union construct, you might think there's no danger of implementing a discriminated union. It is, however, possible to write code with many of the same disadvantages.

Can I use polymorphism in generics?

The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.


1 Answers

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 }
like image 175
Carl Smotricz Avatar answered Oct 12 '22 05:10

Carl Smotricz