13

By looking at the source code for LinkedHashMaps from Sun, I see that there is a private class called KeyIterator, I would like to use this. How can I gain access?

asked Jun 10, 2009 at 21:18

3 Answers 3

45

You get it by calling

myMap.keySet().iterator();

You shouldn't even need to know it exists; it's just an artifact of the implementation. For all you know, they could be using flying monkeys to iterate the keys; as long as they're iterated according to the spec, it doesn't matter how they do it.

By the way, did you know that HashMap has a private class called KeyIterator (as do ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, IdentityHashMap, TreeMap, and WeakHashMap)?
Does that make a difference in how you iterate through the keys of a HashMap?


Edit: In reponse to your comment, be aware that if you are trying to iterate over all key-value pairs in a Map, there is a better way than iterating over the keys and calling get for each. The entrySet() method gets a Set of all key-value pairs which you can then iterate over. So instead of writing:

for (Key key : myMap.keySet()) {
 Value val = myMap.get(key);
 ...
}

you should write:

for (Map.Entry<Key, Value> entry : myMap.entrySet()) {
 doSomethingWithKey(entry.getKey());
 doSomethingWithValue(entry.getValue());
 ...
}

You could also iterate over the values with values() if you want.

Note that since keySet, entrySet, and values are defined in the Map interface, they will work for any Map, not just LinkedHashMap.

answered Jun 10, 2009 at 21:20
2
  • 1
    It just didn't occur to me that I could iterate over a LinkedHashMap until I saw the internal private class. Thanks for the answer though. Commented Jun 11, 2009 at 2:12
  • I didn't know what use is entrySet() of. But, its really useful in almost all places i use a HashMap. Thanks @Michael Commented Nov 6, 2012 at 17:05
4

It's a private class, so you can't directly use it.

 private class KeyIterator extends LinkedHashIterator<K> {

An instance of it is returned when you use the normal Iterator.

myMap.keySet().iterator()
answered Jun 10, 2009 at 21:21
3

You shouldn't use anything that is defined as part of the internal implementation of LinkedHashMap (i.e. in the source code but not defined in the API). What happens if the internal implementation changes in the next release? All of your code using it will break.

You should code to the API and do something like

myMap.keySet().iterator()
answered Jun 10, 2009 at 21:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.