• 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

Hashmap and Generics

 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dope! That's right...thanks!
 
reply
    Bookmark Topic Watch Topic
  • New Topic