java - Why HashSet order always same for my program? -


for tutorial, said:

hashset doesn’t maintain order, elements returned in random order.

but write test program, result same.

import java.util.*;  public class hashsetdemo {      public static void main(string[] args) {         hashset<string> hs1 = new hashset<string>();         hs1.add("a");         hs1.add("b");         hs1.add("c");         hs1.add("d");         hs1.add(null);         hs1.add(null);         system.out.println(hs1);         system.out.println(hs1);     } } 

output:

[null, a, b, c, d] [null, a, b, c, d] 

i tried many times, order same. why? hope can me, in advance!

the reason behaviour hashset backed hashmap, in turn backed array of entry-objects. hash used find index of array. there order of elements in hashset (the order of array), don't have guarantees order is.

as far can tell code, order of hashset determined (or @ least affected) order of computed hashes of elements. then, relatively simple inputs (like single character string), 1 might assume there strict ordering of hashes, give seems natural ordering. more complex objects, , more complex hash computations, hashes more spread, , ordering "more random".

also, it's been pointed out, "no guarantee of ordering" not imply "guaranteed random ordering".

the hashcode-method of string class comes play here, single character strings hashcode int value of 1 char in string. , since char's int values ordered alphabetically, computed hashes of single char strings.


Comments