0

I'm trying to add 10 threads to a set and name them sequentially. But when I debug to see the set, threads are not stored in sequential order. Can someone tell what I am doing wrong?

 Set<Thread> allThreads = new HashSet<Thread>();
        final DemoClass demo = new DemoClass();
    

        for (int i = 0; i < 10; i++) {

            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        demo.getName();
                    } catch (InterruptedException ie) {
                        System.out.println("We have a problem");
                    }
                }
            });
            thread.setName("Thread_" + (i + 1));
            allThreads.add(thread);
        }

        for (Thread t : allThreads) {
            t.start();
        }

        for (Thread t : allThreads) {
            t.join();
        }
    }

When I see allThreads, the threads are jumbled everytime .

  • 2
    Sets have no requirement to store threads in any specific order. Use a list if you want threads to be in the order you added them. – PiRocks Jul 14 '20 at 07:47
  • There doesn't seem to be any reason to use a `HashSet` here, you are guaranteed to have no duplicates anyway, so you just add extra overhead – UnholySheep Jul 14 '20 at 07:50
  • On top of PiRocks said, if you actually have to use a Set, pick one that is ordered, like `TreeSet` (anything implementing `SortedSet`) – Amongalen Jul 14 '20 at 07:53
  • TreeSet will be ordered by the elements' natural order, as I understand the question, the order should be the insertation order, not natural order. – zlaval Jul 14 '20 at 07:59

2 Answers2

1

According to the documentation of HashSet

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.

If you want to keep elements on insertation order, you can use for example ArrayList or LinkedList.

zlaval
  • 1,941
  • 1
  • 10
  • 11
1

Hashset does not maintain order, As mentioned by zlaval - you can use LinkedList or ArrayList.

But if you want to avoid duplicates and also maintain the insertion order, you can use

LinkedHashSet

From docs:

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order)

JavaLearner
  • 272
  • 1
  • 11
  • Thank you to mantioned, it can be life saving some time. Also, if there is no dupe or it does not matter, using arraylist is better coz it has a better performance. – zlaval Jul 14 '20 at 08:08