This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashmap and Generics

 
nico dotti
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>();
 
nico dotti
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dope! That's right...thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic