gudii9
asked on
collection output issue
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class MyHashMapEntrySet3 {
public static void main(String arg[]){
HashMap hm = new HashMap<Integer, String>();
//HashMap hm = new TreeMap<String, String>();
//HashMap hm = new LinkedHashMap<String, String>();
//add key-value pair to hashmap
hm.put(3, "C");
hm.put(1, "A");
hm.put(2, "B");
//hm.put(3, "C");
System.out.println(hm);
//getting value for the given key from hashmap
/* Set<Entry<String, String>> entires = hm.entrySet();
for(Entry<String,String> ent:entires){
System.out.println(ent.getKey()+" ==> "+ent.getValue());*/
//d }
}
}
{1=A, 2=B, 3=C}
i wonder how i got above sorted output based on key all the time first 1 then 2 then 3 key set? please advise
ASKER
What is the answer for this question I could not find there
ASKER
you mean below
http://stackoverflow.com/questions/2817695/how-does-java-order-items-in-a-hashmap-or-a-hashtable
which part of the key it uses
how to see Integer 1 hashcode in documentation where it is preserving order?
same how to see String 1 hashcode in documentation where it is messing order
The ordering is preserved in that particular case since the hash code of 1 is 1, 2 is 2 etc.
http://stackoverflow.com/questions/2817695/how-does-java-order-items-in-a-hashmap-or-a-hashtable
HashMap stores the values using the unique hash-value generated using a part of the key
which part of the key it uses
how to see Integer 1 hashcode in documentation where it is preserving order?
same how to see String 1 hashcode in documentation where it is messing order
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
i am getting same result many many times consistently which makes me believe it is predictable
i am getting same result many many timesI see the same behavior. But, what if we move our code to a different environment? What if we run our code with different Java version? We could see different results.
ASKER
make sense
Also if the hashing function underneath changed you could get different results. That's why the ordered sets and maps use comparable objects so the order can always be guaranteed.
https://www.experts-exchange.com/questions/29006221/hashmap-order.html?anchorAnswerId=42031161#a42031161
https://www.experts-exchange.com/questions/29006221/hashmap-order.html?anchorAnswerId=42031495#a42031495