• Post Reply Bookmark Topic Watch Topic
  • New Topic

Lists of two (or more) types  RSS feed

 
Matan Bar Lev
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I know that I can invoke a list that can contain only one type of objects, for example:
List <ObjectType> mylist = new List <ObjectType>;

Suppose I want to create a list that can contain ONLY two (or more) different types of objects, e.g Strings and Doubles only.
Is it possible to invoke such a list?

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes and no.
You can make a List of any of the subclasses of a particular class.
You can have a raw list which is equivalent to a List<Object> and that can contain any type. Not usually a good idea, however.
But you cannot make a List<String, Integer>.
You might be able to use bounds with the OR operator e.g. String<T extends String | Integer> (not certain) but I don't think that is what you want.

More to the point: why do you want such a List? It sounds like poor design.
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always use a Map<K, V> for this purpose.

Another way would be to create a class Tuple<V, R>,
someting like

class Tuple<K, V> {
K key;
V value;
Tuple(K k, V v) {...}
}

and then you can produce a List<Tuple>.

I found tuples to be a great thing in Scala, certainly missing from Java!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!