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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…