-1

Which rules does HashMap follow to print the sequence.

import java.util.HashMap;

public class MyClass {
  public static void main(String[] args) {
  // Create a HashMap object called capitalCities
    HashMap<String, String> capitalCities = new HashMap<String, String>();

    // Add keys and values (Country, City)
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");
    System.out.println(capitalCities);
  }
}

The output is

{USA=Washington DC, Norway=Oslo, England=London, Germany=Berlin}

Why only this order.

atg greg
  • 1
  • 2
  • also this one https://stackoverflow.com/questions/10710193/how-to-preserve-insertion-order-in-hashmap – JayPeerachai Sep 29 '19 at 13:40
  • Look at `AbstractMap::toString` it simply traverses the map using iterator created from entrySet. However as [docs](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) say *This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time* – Michał Krzywański Sep 29 '19 at 13:41
  • `Hashmap` does not guarantee order as it uses a hash table data structure in which items are inserted and mapped using a hash function such that their position is not necessarily the order in which they were added. If you want to preserve the order you will need to use a `LinkedHashMap` – kyleruss Sep 29 '19 at 13:59

1 Answers1

-1

The basic answer is: It shouldn't really matter. If you are relying on a specific order, you should NOT be using a HashMap, since the order of a HashMap is not reliable.

OrdoFlammae
  • 721
  • 4
  • 13