• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Lists of two (or more) types  RSS feed

 
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?

 
Marshal
Posts: 64483
225
  • 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.
 
Saloon Keeper
Posts: 3250
128
  • 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!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!