I am trying to fix a code, which I wont be able to post it here, So I have a trimmed down version here.
I am getting a unstable output, while using HashMap.
HashMap<Integer, String> test= new HashMap<>();
test.put(1, "one");
test.put(2, "one");
test.put(3, "one");
test.put(4,"four");
test.put(5, "one");
test.put(6, "one");
test.put(10, "one");
test.put(19, "one");
test.put(20, "Sixteen");
System.out.println(test);
HashMap<Integer, String> test3= new HashMap<>(200);
test3.put(1, "one");
test3.put(2, "one");
test3.put(3, "one");
test3.put(4,"four");
test3.put(5, "one");
test3.put(6, "one");
test3.put(10, "one");
test3.put(19, "one");
test3.put(20, "Sixteen");
System.out.println(test3);
Outputs
test --> {1=one, 19=one, 2=one, 3=one, 4=four, 20=Sixteen, 5=one, 6=one, 10=one}
test3--> {1=one, 2=one, 3=one, 4=four, 5=one, 6=one, 10=one, 19=one, 20=Sixteen}---> My desired output.
Why are the results different even though the input values are the same. How is this sorting differing i.e storing of elements?
I am unable to use the second method as the size is dynamic, it keeps on changing based on the application. Can I use TreeMap for the same and get a consistent output for all values.
Why the outputs are different when the size differs –
this because while calling the put method of hashmap indexFor(hash,table.length) is called internally. Table.length is different that means default is 16 but for your second way size is 200. so index will be different.
Please read more in this article
Can I use TreeMap for the same and get a consistent output for all values.
In Treemap gurantees, keys will be ordered and so you will get {1=one, 2=one, 3=one, 4=four, 5=one, 6=one, 10=one, 19=one, 20=Sixteen}
You may use LinkedHashmap if you want to retrieve in the order the way its inserted