• 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

java 1.5 generic and autocasting

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From http://java.sun.com/j2se/1.5.0/docs/guide/collections/changes5.html,

Generics - adds compile-time type safety to the collections framework and eliminates the need to cast when reading elements from collections.
Enhanced for loop - eliminates the need for explicit iterators when interating over collections.
Autoboxing/unboxing - automatically converts primitives (such as int) to wrapper classes (such as Integer) when inserting them into collections, and converts wrapper class instances to primitives when reading from collections.



I think the following code should work, but the compiler complains " Incompatbable type for Object and int or Integer" , what is wrong with me for generic and autocasting?

Thanks,



[ January 17, 2008: Message edited by: Steve Jiang ]
 
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
You declared the HashMap without generics, so it only knows that it returns Object.

If you change that into HashMap<String, Integer>, or even better Map<String, Integer> it should work.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic