The following code produces the out put [1,2]even though hashset is not sorted.
Set set = new HashSet();
set.add(new Integer(2));
set.add(new In
EDIT: As of Java 8 and later, the following is no longer applicable. This proves that you shouldn't rely on undocumented Java behaviours.
This behaviour is caused by several separate reasons:
HashMaps and HashSets are backed up by an arraySo if you add several small (<16) integers to a hashmap/hashset, this is what happens:
i has hashcode iiiNote that if the initial number of buckets is too small, the integers may land in buckets not numbered after them:
HashSet set = new HashSet<>(4);
set.add(5); set.add(3); set.add(1);
for(int i : set) {
System.out.print(i);
}
prints 153.