0

How do you determine the output of a hash set when it is static? For example the following code will output [Harry, Sam, Jim]. Why is it printing in this order? Why does the order change when I change Sam`s name?

public static void hashSetTest() {
    List<String> names = new ArrayList<>();
    names.add("Jack");
    names.add("Jim");
    names.add("Harry");
    names.add("jack");
    names.add("Harry");
    names.add("Sam");
    
    for(int i =0; i<names.size();i++) {
        if(names.get(i).equalsIgnoreCase("jack")) {
            names.remove(i);
        }
    }
    Set set = new HashSet();
    for(int i =0; i <names.size();i++) {
        set.add(names.get(i));
    }
    System.out.println(set);
tHatpart
  • 1,302
  • 3
  • 12
  • 27
  • 1
    Java Sets, just like mathmatical sets, have no fixed order. There is an internal ordering used for easier memory access which is based on the hash code of the objects, but you can't expect it to be consistent, especially when you change the objects. –  Jan 29 '21 at 18:21
  • 3
    Does this answer your question? [Ordering of elements in Java HashSet](https://stackoverflow.com/questions/9345651/ordering-of-elements-in-java-hashset) – lier wu Jan 29 '21 at 18:22

2 Answers2

0

Javadoc of HashSet class:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

See: https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

ag00se
  • 116
  • 1
  • 10
0

A HashSet makes no guarantees on the order of the elements, and you should never rely on it. If you care about the order of iteration, you should consider using a LinkedHashSet instead.

Mureinik
  • 297,002
  • 52
  • 306
  • 350