aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hashmap and Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hashmap and Generics" Watch "Hashmap and Generics" New topic
Author

Hashmap and Generics

nico dotti
Ranch Hand

Joined: Oct 09, 2007
Posts: 124
Hello all, I've noticed that a lot of the Generics stuff that I learned to pass the test a few months back has somehow vanished from my mind! Now I'm needing to use this in a real-world application so I'll pose this as a question: I have a dynamic sql building class that 'has a' Hashmap to keep track of columns and values for a potential insert statement (ie (col1) VALUES (value1). Put differently, it is availabe for appending more and more col/values in building an insert statement.

So my question is how to convert my Hashmap declaration into a generic that can take String for key and Object or any subclass of Object for the value. Here's the non-generic declaration as it now stands:



When declaring my member Map, I need something like Map<String> map = new HashMap<Object>() that will allow for only Strings as keys, and Object or subclasses for values. Is what I just mentioned the correct way to do this? My method that gets these values is simply: public void appendColVals (String columnName, Object Value) and in it's body it 'puts' these into the map.

Thanks all for the help.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by nico dotti:
... When declaring my member Map, I need something like Map<String> map = new HashMap<Object>() that will allow for only Strings as keys, and Object or subclasses for values. Is what I just mentioned the correct way to do this? ...

If you check the API documentation for Map and HashMap, you will see they are defined with generics as Map<K,V> and HashMap<K,V>. So to use Strings as keys and Objects as values, this would be something like...

Map<String, Object> myMap = new HashMap<String, Object>();


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
nico dotti
Ranch Hand

Joined: Oct 09, 2007
Posts: 124
Dope! That's right...thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hashmap and Generics
 
Similar Threads
Generics
Generics
Struggling with generics, "unchecked call to put()"
generics
Difference in "? extends Object" and "Object" in Generics