I know HashMap and ConcurrentHashMap Classes which implements Map Interface. and HashMap is non-synchronized and ConcurrentHashMap is synchronised to lock portion.
Why the output is in a different order? That is because most Map implementations, including HashMap and ConcurrentHashMap, do not store elements in any specific order - so there's no reason to expect the elements to be printed in any particular order.
Shahir Deo wrote:The Output of ConcurrentHashMap is Sorted(or in Order) . but HashMap is not.
It's the other way around.
But that's a coincidence. HashMap and ConcurrentHashMap do not make any guarantees about in which order they return their elements when you iterate over them.
The Output of ConcurrentHashMap is Sorted(or in Order) . but HashMap is not.
As well as Jesper's comments, think about your sample size. 3 items printing out in order doesn't even give a reasonable indication as to whether collection is ordered or not.
Great. But you should still consider this to be a coincidence, because HashMap does not guarantee that it will always iterate over its elements in any particular order.
As I said a small sample doesn't give an indication as to whether it is ordered or not and especially when using low value Integers as keys given the way a HashMap works.
Just to re-iterate what Tony has said, you can easily be tricked into believing HashMap is ordered (when the docs clearly tell you it isn't) when the sample size is small, and the range of values is small. Once the range of values gets distributed wide enough (either because there are lots of values or because the few values you have aren't closely ordered) then you can see there is no ordering. Tony showed an example with a suitably large data set. Here is an example of a small dataset with just 8 value, but those values are distributed over a large range:
Post by:autobot
Just the other day, I was thinking ... about this tiny ad:
a bit of art, as a gift, that will fit in a stocking