0

Does the code below guarantee print keys by insertion order :

LinkedHashMap<String, String> m = new LinkedHashedMap<String,String>();
m.put("A", "Test 1");
m.put("C", "Test 2");
m.put("B", "Test 3");
for (String key : m.keySet()) {
    System.out.println(key);
}

Does the it always print A, C and then B? Or do I need to use an iterator to guarantee that I access the collection in insertion order?

The reason I'm confused is that according to the docs, keySet() returns a Set and there's no order guaranteed when iterating over a Set. Also the keySet() method is inherited from HashMap, so I wonder how LinkedHashMap's keySet() guarantees keys return in insertion order when it is inherited from HashMap.

fat_apupu
  • 64
  • 4
  • I'm not not really sure what you mean by "or do I need to use an iterator" - the for loop is using an iterator. – Andy Turner Aug 04 '16 at 17:48
  • @AndyTurner - I'm referring to "old style" Java iterators. Something like `Iterator itr = c.iterator();` `while (itr.hasNext())`. – fat_apupu Aug 04 '16 at 17:54
  • enhanced for loops are just syntactic sugar that hides that. They use an iterator: see [the language spec](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2), where it says "The enhanced for statement is equivalent to a basic for statement of the form:". – Andy Turner Aug 04 '16 at 17:59
  • Glancing at the code of `HashMap` and `LinkedHashMap`, it seems that `LinkedHashmap` override `HashMap`'s iterator which in turn affect `keySet()`, thus making iteration in ordered form even though it returns a `Set`. Can somebody confirm this as I'm not an expert in Java . – fat_apupu Aug 04 '16 at 18:15
  • You seem to be under the mistaken impression that "set" implies no defined ordering. The [Javadoc of `Set.iterator`](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#iterator()) says "The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)." The [Javadoc of LinkedHashSet](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html) says "This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)." – Andy Turner Aug 04 '16 at 18:26

0 Answers0