arrays - Java - Class Data Type - Sorting Problems -
assume have implemented class edge has 4 attributes, of of type int: from
to
quality
length
.
in program , have created edge[]
array.
i want implement 2 sorting parameters -
one of them sort edge array in descending order of qualities
,
the other sort based on increasing order of lengths
.
i needing these 2 orderings in distinct parts of code.
i using library function arrays.sort()
sorting.
the way know of sorting class data type arrays implement compareto()
within class edge works 1 parameter(quality or length not both).
how can implement 2 sorting functions(2 compareto()
functions ?) , decide 1 called during sorting? in c++ , can make many compare functions , state function go through.how achieve in java?
note: goal sort array of datatype edge using arrays.sort()
, , use 2 different parameters sorting , decide 1 used @ point.
in java, can create 2 classes implements comparator
, defining compare
method, 1 each of sort orders desire.
then can pass instance of 1 of comparator
s arrays.sort
.
if you're using java 8, can pass method reference comparator.comparing
construct comparator
based on getter method.
comparator<edge> lengthascedgecomp = comparator.comparing(edge::getlength);
to make descending sort, can call reversed
.
comparator<edge> qualitydescedgecomp = comparator.comparing(edge::getquality).reversed();