Iteration order of HashSet

后端 未结 9 923
眼角桃花
眼角桃花 2020-11-27 07:32

If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 07:54

    Never ever make assumptions about the iteration order of anything you put into a HashSet because its contract explicitly says that you can't count on it in any way. Use LinkedHashSet if you want to maintain insertion order or TreeSet if you want to maintain a natural sorting order.

提交回复
热议问题