Class Object vs Hashmap

后端 未结 3 969
悲哀的现实
悲哀的现实 2020-12-05 00:50

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

Map cellMap = new HashMap();
         


        
3条回答
  •  旧巷少年郎
    2020-12-05 01:08

    An object has fields (data) and methods (behaviour). If your data consists in a fixed set of cells (A, B and C), then definitely use an object.

    Java is an OO object, and OO design, encapsulation etc. are there to help you build robust, maintainable and fast programs.

    A Map is useful when you must associate a variable number of keys and values. But it's simply a data structure, and doesn't allow you to encapsulate additional behavior.

    For example, you might have a getAAndB() method in your object that returns A concatenated with B. Or you might have methods to transform or query the fields. Or you could pass ABC instances to other objects that make use of them. Using an object ABD with well-defined methods is much easier than using a Map. What are the keys of the map? What are their values? Where is it documented? What if you want to change the keys? How will you detect all the places in the code where these keys are used?

提交回复
热议问题