• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Lists of two (or more) types

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Marshal
Posts: 79174
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 5465
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
reply
    Bookmark Topic Watch Topic
  • New Topic