• 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

Collections

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello guys,

I would like to understand why in this code occurs a exception on line annotated. My keys of map are of type String, then, why I cant't cast the return toArray() Object[] to String[]??

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think when you use public Object[] toArray() of the Collection interface ,which the HashMap class implements, the returned array is type safe meaning you cannot do a conversion to any type but the Object[] type which is default.

So I would suggest you to use public Object[] toArray(Object[] a) method wherein the specified array the toArray() method takes is the type of the array it returns.
ex- set = (String[])mapa.keySet().toArray(new String[0]);
(or)

set=new String[mapa.ketSet().size];
mapa.keySet().toArray(set);

check out the java api for the usage of the above method.I hope this info helps.
 
When I was younger I felt like a man trapped inside a woman’s body. Then I was born. My twin is a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic