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.

9
  • 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. Commented May 16, 2019 at 3:34
  • 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. Commented May 16, 2019 at 3:57
  • 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. Commented May 16, 2019 at 4: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. Commented May 16, 2019 at 4:14
  • 1
    @pippilongstocking see the documentation regarding hashCode() here: docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/… 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. Commented May 16, 2019 at 4:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.