Can I contain two different types in a collection? For example, can I have List< String U Integer > ?
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.
The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.
A Generic class can have muliple type parameters.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With