Ordering of elements in Java HashSet

后端 未结 2 804
迷失自我
迷失自我 2020-11-29 13:13

Why do the second and third sets preserve order:

Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet i = new LinkedHashSet

        
2条回答
  •  无人及你
    2020-11-29 13:52

    The second one (just using HashSet) is only a coincidence. From the JavaDocs:

    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.

    The third one (LinkedHashSet) is designed to be like that:

    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). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

提交回复
热议问题