0

For example,I input 3 Strings:Hagzou Hugzou Jigxng as the keys of a HashMap,

but when I traversing the HashMap by key,the order has been changed:Hugzou Hagzou Jigxng.

Is that possible to make sure the order can not be changed when output the keys?

like this:

input: Hagzou Hugzou Jigxng ###

output: Hagzou Hugzou Jigxng

thx a lot!

Here is my code:

    HashMap< String, Integer > distance = new HashMap< String, Integer >(); 
    Scanner input = new Scanner(System.in);     
    while (true) {
        String city = input.next();
        if (city.equals("###"))
            break;
        distance.put(city, null);
    }
    for (String city : distance.keySet()) {
        System.out.println(city);
    }
fanhk
  • 745
  • 1
  • 10
  • 15

1 Answers1

1

You can use LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

In other words - while LinkedHashMap has a way to access entries by their hash code, like the regular HashMap it also maintains a doubly-linked list and maintain the order of the items insertion. This way when you use its iterator, you'll get the items at the same order you inserted them.

Avi
  • 21,182
  • 26
  • 82
  • 121