List<Map<String,String>> vs List<Object>

Skeptic Scribbler :

What is the difference between using a List<Map<String, String>> vs List<Object> in terms of usage and performance. Suppose I have to create a list of map having only 3 types of key value pair, I can instead create an Object having only 3 properties and make a list of objects.

The question here is out of the two approaches which one should be used in which scenario?

GhostCat salutes Monica C. :

Lets first clarify what we are talking about: it is

List<Map<String, String>> 

versus

List<Foo>

where Foo objects have a number of "properties", that would be stored in a map (as key value pairs) with option one.

In that case, you absolutely go for option two. Simply because good OOP is about creating helpful abstractions, aka models. Meaning: when you have attributes that belong together, then using a class to wrap around them is the natural way to go.

That gives you slight advantages on performance (because you avoid the map access), but the core thing is: it allows you to write compile time checked code. You see:

int foo = list.get(0).map.get("key");

can fail at runtime - you don't know if map contains that key, and if that is an Integer.

But

int foo = list.get(0).getFoo(); // resp. ...get(0).fieldName 

can be checked by the compiler! (yes, those get() calls can still fail at runtime, but that is something you don't get around anyway)

Beyond that: do not worry about performance on this level: first of all, you have to understand what really affects your performance when writing Java code. Because you absolutely want to avoid that "this code is ugly but might give better performance" thoughts sneak into your design. Focus on writing clean code that gets the job done in a straight forward way. Do never write less expressive code because you assume it is faster. When you have a performance problem - profile your code, identify the root cause and fix that.

But do not allow for premature optimization thoughts to impact the quality of your code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433387&siteId=1