1

I'm working with Java 1.8.0_144 and I'm using the debugger in IntelliJ IDEA 2017.2.2. Now my problem is understanding what is going on with a certain piece of code that I've recreated.

I am aware that I may be doing things that I don't need to, but I just wanted to understand what was going on here if anyone can explain it to me. (Code is at the bottom).

When I run this in a debugger, it prints out as I expect:

First

Second

But when I run this normally, it prints out:

Second

First

When I flip the ArrayList near the end of the program and run it, I'm able to get the correct order, but I have no idea why I have to flip it or what's causing this. For some reason, when I run this normally, the ArrayList turns out to be flipped.

Here are the imports I'm using:

java.util.ArrayList;
java.util.Dictionary;
java.util.Enumeration;
java.util.Hashtable;

Code:

public static void main(String[] args) {
    ArrayList<String> arrLs = new ArrayList<>();

    Dictionary<String, Integer> table = new Hashtable<>();
    table.put("First", 1);
    table.put("Second", 2);

    Enumeration<String> enumer = table.keys();
    while(enumer.hasMoreElements()) {
        String str = enumer.nextElement();
        arrLs.add(str);
    }

    for(String s : arrLs) {
        System.out.println(s);
    }
}
Rishi
  • 27
  • 1
  • The linked question is about `HashMap` but the same explanation applies to `Dictionary`. BTW, `Dictionary` is obsolete, you should be using `HashMap` – Jim Garrison Dec 09 '17 at 01:15
  • 1
    Hashtable doesn't maintain insertion order. See [answer](https://stackoverflow.com/questions/6405694/does-hashtable-maintains-the-insertion-order) for details – alexdzot Dec 09 '17 at 01:17

0 Answers0