Reputation: 7853
Consider that I want method foo
to return a LinkedHashMap
(data is ordered by insertion order). The reason being that this Map
will be populated by a database and I want it to reflect the order that is returned from the query. What would be the correct way of defining the signature of the method?
public LinkedHashMap<String, String> foo()
public Map<String, String> foo()
The first would have the advantage of advertising to clients that the map is ordered, while the second would be more general.
Upvotes: 1
Views: 71
Reputation: 30819
It depends on how this method is going to be used/specialized. However, I would recommend the second appoach.
Consider a scenario where this method needs to be overridden to return let's say sorted values (i.e. TreeMap
) or unsorted/unordered values (HashMap
). In this case, we won't be able to override
this method and will have to create another method(s).
Upvotes: 1
Reputation: 13571
Definitely the second one - you should prefer interfaces and hide implementation - if you will decide in the future to use another implementation of Map
you won't need to change anything in another method using this code
Also notice that you are not allowed to overload methods by return type so using general type seems to be appropriate
Upvotes: 1