java - Sorting an array of objects by more than one field -
say have array holds 10 objects each 3 values supposed represent league table
team1 20 5 team2 21 6 team3 21 8 team4 23 8
i want sort first value (points) , 2nd value (goal difference).
arrays.sort()
work if override compareto()
, write piece of custom code.
is there easier way? converting list etc.?
creating comparator
correct way solve this. whether use arrays.sort()
or collections.sort()
you.
i suggest former avoids conversion list , preferable.
i recommend don't solve implementing comparable
in object, sounds display issue , embedding sort order in object not wise.
an example (untested) implementation might be:
public class examplecomparator implements comparator<yourobject> { public int compare(yourobject o1, yourobject o2) { if (o1 == null || o2 == null) { throw new nullpointerexception(); } if (o1.getvalue1() != o2.getvalue1()) { return integer.compare(o1.getvalue1(), o2.getvalue1()); } return integer.compare(o1.getvalue2(), o2.getvalue2()); } }
Comments
Post a Comment