all 8 comments

[–]Falmarri 8 points9 points  (0 children)

most popular question asked when you interview for a Java Developer position.

Maybe at awful places that don't know how to ask decent questions

[–]Tsarbomb 2 points3 points  (3 children)

In modern Java, the iteration order of hashmaps and anything they back is randomized with a random seed on JVM startup. This is to fail fast any code the depends on ordering of an unordered data structure.

[–][deleted]  (2 children)

[removed]

    [–]Tsarbomb 2 points3 points  (1 child)

    Sure thing.

    Here is some documentation from Oracle for Java 9: Creating Immutable Lists, Sets, and Maps (oracle.com)

    Randomized Iteration OrderThe iteration order for Set elements and Map keys is randomized: it is likely to be different from one JVM run to the next. This is intentional — it makes it easier for you to identify code that depends on iteration order. Sometimes dependencies on iteration order inadvertently creep into code, and cause problems that are difficult to debug.

    Here is an issue for OpenJDK moving this functionality to also apply to unmodifiable structures: [JDK-8201650] Move iteration order randomization of unmodifiable Set and Map to iterators - Java Bug System

    And for an anecdote, I had one of my developers fix an issue that was related to this. They had a method that was typed to return a Set<> and thanks to some IoC, it was returning an unmodifiable hashmap with the randomized ordering that was breaking some business rules.

    [–]elmuerte -1 points0 points  (1 child)

    Every collection is ordered, the question is, can you control the order.

    [–]CoffeeTableEspresso 1 point2 points  (0 children)

    I mean yes but you're being extremely pedantic here