This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting generics  RSS feed

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • 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.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • 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 Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the very clear explanation
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!