where need to use collections.sort() and comparable and comparator interfaces in java collection? -
i got understanding of collections gone through articles.
'm confusing should implement collections.sort() method , need use comparable interface(compareto() , comparator interface (compare()).
comparable interface compare , reference object comparator compare 2 objects.
i know situation need use methods ?
thanks,
you should not implement collections.sort()
; method built-in java. call method without supplying comparator
sort natural order, if it's comparable
. else, supply comparator
sort comparator
's way.
you should have class implement comparable
, provide compareto
method if class has natural ordering, indicated in comparable
javadocs. example integer
, double
, have natural mathematical ordering.
you should create class implements comparator
when cannot make class of object sort comparable
or when want present ordering alternative natural ordering, or when want impose order when there no natural ordering. example reverse natural order (say, sort descending, largest smallest). example data object multiple fields, want sortable on multiple fields, e.g. person
object firstname
, lastname
: have comparator
sorts on lastname
first, , sorts on firstname
first.
Comments
Post a Comment