• 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

Casting generics

 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A little doubt about generics.

I have a class containing a Map of String to Object.
One of the record in the map is of type List<MyRecords>;

Object mylist = myMap.get("myrecord");

This will do, but what I want to do is :

List<MyRecords> mylist = (List<MyRecords> myMap.get("myrecord");

The compiler keeps on complaining about that cast.
It's only a warning that I can suppress, but I was wondering if I'm missing something here.
My map does not contain only lists, it contains any kind of stuff.
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

My map does not contain only lists, it contains any kind of stuff.


The consequence of this of course is that the compiler can't be *sure* that the Object that you obtain from the Map is a List. Therefore the cast to a List<MyRecords> is an unchecked cast and the compiler must warn you about it. The only way to eliminate the warning is to make the Map typesafe by specifying at compile time (using generics) that all the keys are Strings, and all the values are List<MyRecord>. Since apparently you can't do that, you'll have to live with, or supress, the warning.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the very clear explanation
 
reply
    Bookmark Topic Watch Topic
  • New Topic