javahashmapiteratorkeyset

About HashMap collection's keySet() method


Map<K, V> map = HashMap<K, V>();

Set<K> keySet = map.keySet(); //'map' is  parameter of HashMap object

Iterator<K> keyIterator = keySet.iterator();

I'm studying about how I can get key by 'Iterator'. The code above is part of that.

but [Set<K> keySet = map.keySet();] <- in this part

Isn't it that HashMap's keySet() method is what Set interface's keySet() method is redefined in HashMap?

but I can't find it in JAVA API document's method menu.


Solution

  • You seem to be making this more complicated than necessary.

    A Map<K,V> has some keys; it will hand you a view of those keys as a Set<K>.

    That Set<> necessarily implements the Set<> interface, which has Iterable<> as a subinterface. Therefore you can get an iterator over the Set.

    Since it's an Iterator, then if you iterate it, it will eventually yield every possible key. That is:

    while (iterator.hasNext()) {
         key = iterator.Next(); // <<< this is the key
          :
    }
    

    But what are you actually trying to do?

    i'm studying about how i can get key by 'iterator' above is part of that

    The point of the Map and Set interfaces is that you can access them directly by key.