HashMap JVM Differences

Although Java slogan's is "Write once, run everywhere" , to emphasize the cross-platform benefit, in practice unfortunately this is not totally true.

One known difference between Sun and other JVMs is the HashMap order output.

When  executing the exact same program and iterating though  the same exact same HashMap input, a Sun JVM will produce a different output than another JVM.

See as example the code below:

 
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class HashMapTest {

        static HashMap<String, String> result = new HashMap<String, String>();
        static Iterator<Map.Entry<String, String>> entryIter;
        static HashMap<String, String> thash = new HashMap<String, String>();

        public static void main(String[] args) {

                for (int i = 0; i < 10; i++){
                        thash.put(Integer.toString(10 - i), "abc");
                }

                result.putAll(thash);

                entryIter = result.entrySet().iterator();
                while (entryIter.hasNext()) {

                        Map.Entry<String, String>  entry = entryIter.next();
                        String val1 = entry.getKey();
                        String val =  entry.getValue();
                        System.out.println("Key: "+ val1 + " Value: "+val);
                }
        }

}






Compiling and executing this code with Sun Java will create the following output:

Key: 3 Value: abc
Key: 2 Value: abc
Key: 10 Value: abc
Key: 1 Value: abc
Key: 7 Value: abc
Key: 6 Value: abc
Key: 5 Value: abc
Key: 4 Value: abc
Key: 9 Value: abc
Key: 8 Value: abc

While whether doing the same thing with IBM Java you should get:

Key: 10 Value: abc
Key: 9 Value: abc
Key: 8 Value: abc
Key: 7 Value: abc
Key: 6 Value: abc
Key: 5 Value: abc
Key: 4 Value: abc
Key: 3 Value: abc
Key: 2 Value: abc
Key: 1 Value: abc

I don't want to enter in merits of which one is right and which one is wrong. Just want to alert people that this issue can cause serious differences in programs output.

Comments

Popular posts from this blog

Slope One

Apache Mahout

Error when using smooth.spline