• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Deseriaziling parameterised/generic collections

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I wrote this test code to refresh my memory on serialization, but also because I was curious if you could deserialize parameterised/generic collections (I was expecting not since generics in Java only offers compile time protection against putting the wrong stuff in a collection):



As you can see, the line which reads the HashMap back generates a warning. The warnings go away if I simply attempt to cast it to a non-generic Map/HashMap. But what if I want to retain the benefits of generics after deserializing this collection, without generating a compiler warning?

What would be the safe/proper way to do this?

thanks,

Andy
 
Andrew Ebling
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, and adding an "instanceof" check after reading the object back doesn't work either
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Andrew,

There are no Type safe collections at runtime.
At complile time you can restrict the code.

readObject returns the HashMap encapsulated by Object which lost its type long back the program starts running.

Hence
HashMap<String,String> hm = (HashMap<String,String> ois.readObject();
warns you may not get HashMap<String,String>.

Its our risk factor.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Srini,

It means if we cast Object what we get back from the readObject() method,
to the (Map<String,String> , it gives warning and the code can't compile without warning.

I was also stuck to the same warning some time ago.
Isn't there any safe way to do casting? (It is my query from you!)

As Andrew says only casting to (HashMap) does compile the code without warning; seems nice, although I have not checked that... Let me check




Regards,
cmbhatt
[ April 21, 2007: Message edited by: Chandra Bhatt ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic