Any implementation of Ordered Set in Java?

后端 未结 10 1934
说谎
说谎 2020-12-01 09:00

If anybody is familiar with Objective-C there is a collection called NSOrderedSet that acts as Set and its items can be accessed as an Array

10条回答
  •  失恋的感觉
    2020-12-01 09:17

    Try using java.util.TreeSet that implements SortedSet.

    To quote the doc:

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

    Note that add, remove and contains has a time cost log(n).

    If you want to access the content of the set as an Array, you can convert it doing:

    YourType[] array = someSet.toArray(new YourType[yourSet.size()]); 
    

    This array will be sorted with the same criteria as the TreeSet (natural or by a comparator), and in many cases this will have a advantage instead of doing a Arrays.sort()

提交回复
热议问题