0
// Using entrySet() to get the entry's of the map
// m is previously created Map.

Set<Map.Entry<String,Integer>> s = m.entrySet();
for (Map.Entry<String, Integer> it: s)
{ 
    String str = it.getKey();
 }

Map.Enty is just the interface.

An interface doesn't have the implementation of the method getKey();

why the code above works? Like how the compiler knows the behavior of getKey()?

Syfer
  • 4,262
  • 3
  • 20
  • 37
Lin Paul
  • 49
  • 8
  • Because `Node` in `HashMap.java` implements `Map.Entry`, so I don't know what you're asking. – Jacob G. May 11 '18 at 01:41
  • There is an implementation to `Map.Entry` which is being used. If you step through your code with a debugger, you can probably find out which class, and even step into the source code for that class. – Tim Biegeleisen May 11 '18 at 01:43
  • 3
    so you know the word "interface" but apparently you haven't studied why it exists and how it can be used. – Patrick Parker May 11 '18 at 01:56
  • 2
    This is polymorphism. There is a difference between the "actual type" and the "apparent type". In short, the code you're reading deals with the apparent one. Any implementer of an interface can be used in such a way. – ChiefTwoPencils May 11 '18 at 02:13
  • And to break your world, interface can implement method since Java 8. – AxelH May 11 '18 at 05:43
  • to " If you step through your code with a debugger, you can probably find out which class " . Could gdb help me find which class the compiler is using? – Lin Paul May 11 '18 at 15:14

1 Answers1

0

As code shown below:

static class Entry<K,V> implements Map.Entry<K,V>

This code is from HashMap, and if we put a new K-V Entry, the HashMap will create a new instance of HashMap.Entry :

void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}

So, every it variable in your for-each loop is a instance of HashMap.Entry class which implements Map.Entry interface.

Hello World
  • 129
  • 7
  • Hi, I am still confused. What the dot . means? Like Map.Entry? – Lin Paul May 11 '18 at 02:42
  • Interface Map.Entry All Known Implementing Classes: AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry CIted from https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html this website doesn't mention Entry class implements Map.Entry – Lin Paul May 11 '18 at 02:43
  • You can find the answer at https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html and https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html – Hello World May 11 '18 at 02:52
  • And read the tutorial written by oracle : https://docs.oracle.com/javase/tutorial/java/index.html – Hello World May 11 '18 at 02:55