0

Helllo,

I have an ArrayList of OBJECTS (teams). They are football teams and I would like to sort them out through their points. Obviously I am fully aware ArrayLists are sorted via the order they are inserted.

But I have a TEAM class that has gamesWon, gamesLost, gamesTied and points based on a match result.

I have everything ready but figured that sorting out an ArrayList through it's points would be a cool feature to make.

I have read the Collections.sort(myArrayList) online, but this sorts based on ONE type of variable, and since I have objects within the ArrayList, I would like to sort this out.

Thank you.

Marco

asked Nov 19, 2012 at 0:41

2 Answers 2

3

You should define a Comparator for this.

public class PointsBasedTeamComparator implements Comparator<Team> {
 public int compare(Team t1, Team t2) {
 //return the result of points comparison of t1 and t2
 }
}

And use it as follows

Collections.sort(teams, new PointsBasedTeamComparator());
answered Nov 19, 2012 at 0:46

Comments

2
  1. Define a java.util.Comparator<Team> that implements compareTo with the value that you want to check.

  2. Use the sort method that accepts the Comparator<Object>. It will use the compareTo method of your Comparator, and not the one defined in Team (if any).

  3. Enjoy!

answered Nov 19, 2012 at 0:44

2 Comments

I think this calls for Comparator rather than Comparable; being Comparable implies that the objects have a single natural order, whereas a Comparator is just some particular way of sorting them, of which there could be several.
Ok this is a bit confusing as I have never used Comparator, etc but I am going to read a bit more before I do. Thanks a bunch guys!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.