Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

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 }
    }
}

Open in new window


{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
Avatar of rrz
rrz
Flag of United States of America image

Avatar of gudii9

ASKER

What is the answer for this question I could not find there
Avatar of gudii9

ASKER

you mean below
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
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

i am getting same result many many times consistently which makes me believe it is predictable
i am getting same result many many times
I 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.
Avatar of gudii9

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.