#Comparator works differently for collections and sets?

1 messages · Page 1 of 1 (latest)

sour thunder
#

Hi, am very confused by the Comparator. For Sets, I can use it when initialising a TreeSet but for ArrayList ill need to use Collections.sort(list, comparator). WHY?!

mystic fulcrumBOT
#

This post has been reserved for your question.

Hey @sour thunder! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

mental canyon
#

TreeSet is sorted, Lists are not, they are ordered, you need to explicitly sort them as a one-time action

#

this is kinda like asking between TreeSet and HashSet. TreeSet is just specifically, on its own, sorted.

#

also, Sets are Collections.

#

i feel like you're missing the point of all these structures. they all have distinct semantics, but you're treating them all as "sequence" and expecting them to behave similarly.

sour thunder
mental canyon
# sour thunder You are probably correct there. I am very confused about why you sort them diffe...

you're misunderstanding a bit
"sorted" / "ordered" refer to the nature of the structure
HashSet is unsorted and unordered, you can't guarantee or expect any specific order of elements when you iterate over it (for example)
LinkedHashSet is ordered, you can specify an order of the elements (being the order of insertion in this case)
TreeSet is sorted, you can specify a sorting for the elements (and the structure will maintain that sorting as you add or remove elements)

List is ordered like LinkedHashSet, but its order is more manipulatable, it's not just the order of insertion
so Collections.sort and List.sort are methods that change the order of the List, using the given Comparator as a reference to how they should be ordered