Was ist der Unterschied von Hashset, LinkedHashset und treeset, bezüglich wie die Elemente im Set gespeichert werden, also die Reihenfolge?

1 Antwort

Zu HashSet:

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.

Bei einem Hashset ist keine Ordnung vorgegeben.

Zu LinkedHashSet:

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).

Bei einem LinkedHashSet werden die Elemente in Einfügereihenfolge gespeichert.

Zu TreeSet:

The elements are ordered using their natural ordering, or by a
Comparator
provided at set creation time, depending on which constructor is used.

Bei einem TreeSet werden die Elemenete gemäß einer natürlichen Ordnung gespeichert.

Quellen:

https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/HashSet.html

https://docs.oracle.com/javase/jp/13/docs/api/java.base/java/util/LinkedHashSet.html

https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/TreeSet.html