1


When we output the values of a simple hashtable why it's values output in decremented order of it's key?

And how can I output in incremental order?

   Hashtable<Integer, String> htable = new Hashtable<>();
        htable.put(100, "Dil");
        htable.put(200, "Vidu");
        htable.put(300, "Apeksha");
        htable.put(400, "Akalpa");
        htable.put(500, "Akash");
        for (Map.Entry entry : htable.entrySet()) {
            System.out.println(entry.getKey() + "  :  " + entry.getValue() + "  :  " + entry.hashCode());
        }

Output

500  :  Akash  :  63312920
400  :  Akalpa  :  1962708790
300  :  Apeksha  :  861238907
200  :  Vidu  :  2666092
100  :  Dil  :  68611

Also Can you please explain what actually hashcode is? Is that a random number set to make each result is unique?

Thank you.

Dil.
  • 1,996
  • 7
  • 41
  • 68
  • 1
    There is no guarantee regarding the order you get when you iterate the keys in a Java HashMap, and the documentation states this. If you want a sorted map, look into using something like `TreeMap`. – Tim Biegeleisen May 16 '19 at 03:34
  • @TimBiegeleisen thanks. Yes I easily can. I was just following a tutorial and wandered what was the reason. – Dil. May 16 '19 at 03:38
  • I didn't give an exact duplicate, but the explanation is the same. – Tim Biegeleisen May 16 '19 at 03:39
  • 1
    Please use `LinkedHashMap` as it maintains insertion order. `Hashtable` and `HashMap` does not maintain insertion order.`entry.hashCode()` represents unique code for a given key-value pair. Technically, it is `XOR` between key hash code and value hash code. – Anshul Singhal May 16 '19 at 03:57
  • @anshul what did you mean by `it isXOR between key hash code and value hash code` ??? – Dil. May 16 '19 at 04:02
  • 1
    This is logic to calculate hash code (i.e. unique number) for Map.entry object and logic is First, get key hash code and then value hash code and then perform XOR operation between the two hash codes. – Anshul Singhal May 16 '19 at 04:09
  • 1
    @pippilongstocking Hashcode is a output generated by a hash function, in case of hashtable the key is the input to a hash function. – Naruto26 May 16 '19 at 04:14
  • 1
    @pippilongstocking see the documentation regarding `hashCode()` here: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Object.html#hashCode() It is inherited from the `Object` class. Note that it is not guaranteed to be unique across any set of objects, but there is a good chance that it will be. – David Mordigal May 16 '19 at 04:17
  • I have added [dup](https://stackoverflow.com/questions/2144776/is-the-order-of-values-retrieved-from-a-hashmap-the-insertion-order) where someone else observed (serendipitous) key ordering. The answer says why it happened ... and that you can't rely on it. – Stephen C May 16 '19 at 04:20

0 Answers0