Roland
Roland

Reputation: 7853

Signature of method that returns a LinkedHashMap<K,V>

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?

  1. public LinkedHashMap<String, String> foo()
  2. 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

Answers (2)

Darshan Mehta
Darshan Mehta

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

m.antkowicz
m.antkowicz

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

Related Questions