Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

java - Class Object vs Hashmap

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 ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...