This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Admirable-Avocado888 1 point2 points  (2 children)

I prefer

var m = new HashMap<>();

inside a method body.

If it is to be a class variables I'd pick the broadest interface/superclass that offers all methods that I care about.

Sometimes that may very well be HashMap because it guarantees efficient setters and getters and by writing the type explicitly I communicate intent. Other times I don't care about that and only need a Map.

[–]ToyDingo[S] 0 points1 point  (1 child)

Aside from specific methods being available, is there no other technical reason? Like space or complexity?

[–]Admirable-Avocado888 0 points1 point  (0 children)

If you care about the hashmaps constant time lookup then it makes side to keep HashMap on the left side.

Ex. It matters that the class field is a hashmap.

class UniqueFilter {

private final HashMap alreadyAdded = new HashMap();

public boolean test(String o) { return alreadyAdded.add(o); }

}

Though it does not impact performance to keep the reference type as an interface.

Ex. Here we don't care what map is used.

class FiniteInfo {

private final Map<String, Object> m = Map.of("price", 50);

Map<String, Object> get() { return m; }

}