aspose file tools*
The moose likes Beginning Java and the fly likes HashMap type safety Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashMap type safety" Watch "HashMap type safety" New topic
Author

HashMap type safety

Sacha Genoud
Greenhorn

Joined: Jul 06, 2012
Posts: 2
Hello

i create a map with



then i fill it with values


then i want to read a value like 3456


then i get


How can a value be long in a Map wich is with type safety created?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36486
    
  16
Welcome to the Ranch
What is req? What is the return type of getValues()? Does it return a Map with a different generic type, or even a raw type?
It would appear you are getting a String-Long pairing. The valueOf method takes int or String parameters; if you pass an Integer, that would be unboxed to int, but you can’t unbox a Long to an int. So the JVM tries to cast the result to a String, and that doesn’t work.

I think the problem is filling the Map inappropriately from a (??) database request. Did you get any compiler warnings for that code? If you do, you should heed them. If there are any warnings, then type‑safety cannot be guaranteed, as you see here.

By the way: house numbers are not integers. They are not numbers of any sort. I have had friends living at no 11a, at no 32a, at no 2½, etc. House numbers are Strings.
Sacha Genoud
Greenhorn

Joined: Jul 06, 2012
Posts: 2
Hello Ritchie

thank you for your quick answer.

Now it works, but is it a good idea?


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36486
    
  16
Sacha Genoud wrote:Hello Ritchie

thank you for your quick answer.
You’re welcome
Now it works, but is it a good idea?


No.

You need to find out why you are getting the cast exception. Also, tell us whether there are any compiler warnings.
Look at the chapter in Effective Java about generics. Bloch says Java™ is completely type-safe as long as there are no warnings from the compiler and you have not used the suppress warnings annotation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashMap type safety
 
Similar Threads
Problem going from 1.5 to 1.4.2
IllegalArgumentException: more than 10 parameters
generics and maps
HashMap bean with generic type parameters
Alternate way of inserting the values in map?