java.util.Map.Entry
as I know is a public static interface
in java.util
package that
returns collection view of a map but as far now I am confused with the static interface
and as it is Map.Entry is it an inner interface if so how do we have inner static interfaces in java
Look people I am confused Please help me in any possible way you can.
The definition of
Entry
happens to live inside the definition ofMap
(allowed by java). Beingstatic
means you don't need an instance ofMap
to refer to anEntry
.It's easiest to show how to use
Map.Entry
by an example. Here's how you can iterate over a mapInner interfaces are implicitly public and static.
You can have inner interfaces as follows :
You can access the above inner interface(B) by A.B where A is a class or an interface according to the above two cases.
For example,
Yes, it's an inner interface of the
Map
interface.For more information about interfaces, see the Interfaces tutorial and this Static Nested Interfaces article.
There isn't really anything to be confused about.
Yes, Java allows interfaces to be members of classes or other interfaces.
No, that does not mean anything special. It changes absolutely nothing about how you can use such an interface or what you can do with it.
It only changes the name of that interface and creates a strong conceptual link between it and its enclosing type. In this case, a
Map.Entry
represents an entry of aMap
. The designers of the API apparently felt that it made sense to stress this connection by making it a member type.Java allows nested interfaces. You can nest them into classes or interfaces. For instance,
Map.Entry
is a nested interface defined in theMap
interface.Map
implementations (TreeMap
,HashMap
) provide private implementations ofMap.Entry
, which are not visible outside the class.Bohemian's answer addresses how to use
Map.Entry
.Example:
Bar is a nested interface. Nested interfaces are static by default, so you could as well write:
Now, what static in this context means is that the interface is a static member, i.e. a member of the class.
You can do this with classes as well:
Here, Node is even private, meaning it's only visible within Tree. So, what's the benefit of this? Why not make Node a public class? Because of better encapsulation. First, the Node is an implementation detail of the Tree, so you don't want it to be visible. Second, if you expose Node via a public API, some client (programmer) could use it in his code. Now, he has a hard dependency on this class. If at some point you want to change the representation of you Tree, and you change/remove the Node class, the client code's may break. And last but not least, your public API becomes smaller, which is also desirable.
So, when to use static member classes/interfaces? Mostly, if you build some sort of Composite object (like a Tree, or a Linked List) or when the class only makes sense in the context of the outer class.