Java Class Object vs HashMap – Key Differences Explained

classhashmapjavaobject

Is it good to use hashmap instead of using the object class……
Using Hashmap….

Map<String, String> cellMap = new HashMap<String, String>();
int j = 0;
while (cellIter.hasNext()) 
{
   HSSFCell myCell = (HSSFCell) cellIter.next();
   cellMap.put(columnMap[j], myCell.toString());
   j++;
}

And using object class…..

ABC abc= new ABC(); 
abc.setA(myRow.getCell(0).toString());
abc.setB(myRow.getCell(1).toString());
abc.setC(myRow.getCell(2).toString());

Please tell me in the context of application health, memory requirement etc …

Best Answer

This depends a lot on what you are trying to achieve: for flexibility, hash map is better. But the flexibility comes at a price: hash map is also larger and slower than a class with the identical number of strongly-typed fields.

  • Hash map has larger memory footprint than a class with identical number of fields
  • Hash map forces boxing on primitives
  • Hash map is slower to create and access

There is also an impact on readability: when you business logic is specific to a class with a fixed number of fields, a special-purpose class clearly wins; when the fields are configured dynamically, hash table is your only option. You could also have a hybrid design, when an object uses a hash map for its storage internally, presents nicely named fields externally, and exposes semantics to add more "fields" as you go.

To summarize, before you decide to go with a hash map for its flexibility, you should decide if you really need all that flexibility in your design. Sometimes, the answer is "yes", and sometimes it is "no"; there is no "one size fits all" solution to this.

Related Question