• 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

How to know the type at runtime?

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have list = new ArrayList()
list.add(new ArrayList<Integer>);
list.add(new ArrayList<String>);
list.add(new ArrayList<Double>);

now the question is how do i know at runtime which list is of which type at runtime after iterating thr the main list
 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lists maintain the sequence of elements.
So list.get(0) will give you the integer list.
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generic is a compile time check
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generics in Java work with type erasure, which means that the compiler will essentially remove the type parameters. At runtime, an ArrayList<String> looks like a plain old ArrayList to the JVM. There's no way of knowing that it it actually an ArrayList<String>, because the compiler has thrown the information about the String type parameter away.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only thing you can do is guess, based on the elements. However, even if all elements are Strings, that does not mean it is an ArrayList<String> - it can also be an ArrayList<Object>, ArrayList<Serializable>, ArrayList<CharSequence> etc.
 
reply
    Bookmark Topic Watch Topic
  • New Topic