Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better HashMap vs POJO ( Getter Setter , Model Class) in Java and Android

In some cases i suffered the operation at that time,

We can use the both HashMap or Model Class (POJO) as a ArrayList Generic Like ArrayList<HashMap<K,V>>() OR ArrayList<ModelName>().

Can you suggest me which is the better as a memory point of view and performances vise.

I know both are the better in it place, but i just want to know if i have option to take both alternative.... which will the better ?

e.g. Suppose i have 2 variable both are string in POJO class, and same both are for HashMap.

so we have the list objects Like..

  final  ArrayList<Abc> listAbc = new ArrayList<Abc>();

 for(final int i=0;i<2;i++){
    Abc modelAbc = new Abc();
    abc.setName("name");
    abc.setLastName("lastName");
    listAbc.add(modelAbc);
  }

in this case i have to take two object of ABC class,

And in HashMap with List object it will...

final ArrayList<HashMap<String,String>> listMap = new ArrayList<HashMap<String,String>>();

for(final int i=0;i<2;i++){
 HashMap<String,String> hashAbc = new HashMap<String,String>();
 hashAbc.put("NAME","firstName");
 hashAbc.put("LASTNAME","lastName");
 listMap.add(hashAbc);
}

in this case i have to use two object of HashMap.

Now tell me which will i have to use for better performance? Which is occupier of high memory ?

like image 900
GovindRathod Avatar asked Aug 07 '14 08:08

GovindRathod


1 Answers

In general, you use a Collection (List, Map, Set) to store objects with similar characteristics, that's why generics exist. So using a Map to store objects of several classes forces you to cast every object you have stored when you are getting it, which is not the cleanest code we can write. Also, even using a HashMap, where the objects are easily fetched using the hashCode value, the access is slower than to a Java Bean attribute... and you have always to ensure that those objects have a good hashCode() generator. But anyway, I cannot imagine when this could be a bottleneck in performance in a regular application.

So my recommendation is using a Java Bean every time that you know in compilation time how many attributes you are going to store and their classes, using the Map to store elements of the same class.

For example, if you have a DB table with users, and you want to "cache" the users to access to anyone of them quickly, you could do something like this:

class User {
    long id;
    String name;
    ... //other attributes

   //setters and getters
}

And then store them in a Map to have a fast access to them by their id:

Map<Long,User> usersMap= new HashMap<>();
...
usersMap.put(user.getId(),user);
like image 162
Pablo Lozano Avatar answered Oct 30 '22 23:10

Pablo Lozano