The general answer is this:
With HashMap obj =new HashMap()
, the writer is required to think about HashMap.
With Map obj =new HashMap()
he is required to think about Map and HashMap.
Does the scenario justify the added cost? What's the plot?
(The rookies who go "yay now we don't have to think about the class!" ship with additional bugs in their programs.)
Does the added cost result in savings?
In the case of (
java.util.
)
Map
vs
HashMap
, it is unequivocally no.
Map
is so big and
HashMap
so small, that you have nothing to save but much overhead to lose if you use both of them within private code.
In the general case of A
vs B
, if they have a significant difference in size and/or there is a significant amount of private code using A
instead of B
, then by employing both you gain to the extent of their difference and the amount of code using it.
For example, java.util.Queue
vs .LinkedList
:
private LinkedList/Queue obj = new LinkedList();
obj. //..
Would it be better to leave the variable as LinkedList or to use Queue?
With one line of usage, it can go both ways. But it quickly gets obvious which is a better choice when the amount of code increases:
private LinkedList/Queue obj = new LinkedList();
obj. //..
//..
//..
obj. //..
//..
//..
obj. //..
//..
//..
obj. //..
//..
//..
obj. //..
//..
The code usage could get so much that you'd need to factor it into it's own function:
obj. //..
//..
//..
obj. //..
//..
//..
Function1(obj);
//..
//..
}
private void Function1(Queue obj){
//..
//..
obj. //..
//..
//..
}
..or even multiple functions:
private void Function1(Queue obj){
//..
//..
obj. //..
//..
//..
Function2(obj);
//..
Function3(obj);
//..
Function4(obj);
//..
}
When writing all of those code in those functions, the writer never once have to think in terms of LinkedList. The only times when its required to think in terms of LinkedList are at the callsites of those functions.
Since the size difference between Queue and LinkedList is significant and the usage of Queue here plentiful, the overhead of having to think in two separate constructs (compared to simply using LinkedList throughout) is relatively small.
Tldr: For Map
vs HashMap
, Nopppe.
And it's interesting that this question always appears every now and then yet I see no one ever talking about AbstractMap as if it doesn't even exist, and indeed yes it doesn't need to exist. And if only Map
was 10 characters longer and Hashmap
10 characters shorter, no one would be talking about using Map
for private code either just as no one talks about AbstractMap
because those extra keystrokes would make people realize the obviousness that Map obj = new HashMap()
for private code is senselessly redundant. Reminding me of tards who appear with an interface for every single method and every single combination of it ..a tale for another day..