This is a simplified version of java.util.Map
public interface Map {
interface Entry{
int getKey();
}
void clear();
}
My question is why it is done that way?
How the inner interface should be implemented? Can I just implement the inner one?
I'm going to be... terribly theoric here... so keep an open mind, please. A separate Entry
interface would decouple that concept from the context it is meant to. Don't think only about the interface but about its implementations. Take for example the Entry
inner static class defined in HashMap
:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
(...)
}
This Entry
class is not intended to be used outside, and the interface it implements represents a service contract meant only for internal use amongst Map
s, in particular because Map
is an interface itself and needs a little abstraction to let the particular implementations define the kind of entry that they will use.
Indeed, I bet you're wondering "Sure, but an entry can be used in many situations, specially when you need a Key - Value pair". This is, in fact, true, but I personally agree with the current design decision as it provides everything that is required to implement a Map
in a single place.
Here Map
is used also as a namespace. It's because Entry
does not belong to the global scope - there are many other entities that are Entries
and are not necessary Map
's entries. This indicates that Entry
represents entries related to the Map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With