Sort ArrayList of objects through one of its instance variables

余生颓废 提交于 2019-12-25 18:25:19

问题


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


回答1:


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());



回答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!



来源:https://stackoverflow.com/questions/13446228/sort-arraylist-of-objects-through-one-of-its-instance-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!