I googled, the only thing I found:

The LinkedHashSet class extends the HashSet class without adding any new methods. The class maintains a coherent list of elements of the set in the order in which they were inserted. This allows you to organize an ordered iteration of the insert in the set.

But did not understand. Can anyone explain in more detail?

  • one
    Try to answer yourself a simple question. In what order will the elements in HashSet ? - D-side
  • in which they wrote - Anton Sorokin
  • as added, so it will be - Anton Sorokin
  • four
    And now test your hypothesis. - D-side
  • one
    why the question is so much mined? it is no worse than dozens of similar but with a different rating sign .. - 4per

1 answer 1

The main difference is that LinkedHashSet preserves the order of insertion of elements, but HashSet does not. At the same time, LinkedHashSet as well as HashSet uses a hash table, unlike the same TreeSet .

HashSet example:

 HashSet dset = new HashSet(); dset.add(new Dog(2)); dset.add(new Dog(1)); dset.add(new Dog(3)); dset.add(new Dog(5)); dset.add(new Dog(4)); Iterator iterator = dset.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } 

Result: 5 3 2 1 4

LinkedHashSet example:

 LinkedHashSet dset = new LinkedHashSet(); dset.add(new Dog(2)); dset.add(new Dog(1)); dset.add(new Dog(3)); dset.add(new Dog(5)); dset.add(new Dog(4)); Iterator iterator = dset.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } 

Result: 2 1 3 5 4

  • Does HashSet always give out 5 3 2 1 4 with this filling? or if you add a second cycle, the order may be different? - Grundy
  • @Grundy the answer to this question is not defined. Yes, and irrelevant. - D-side
  • @Grundy no data structure makes random traversal intentionally. Of course, it will be the same if you do not change the collection. - Pavel Mayorov
  • @Grundy well, the official documentation states that due to the use of hash tables, the order will not be guaranteed to be constant in time. So I think the answer is yes, the order may be different, though theoretically. In most cases, the result will be the same. - DEADMC