要使自己的类拥有排序功能,就要实现comparator接口,重写compare方法。
原题链接:Java Comparator
Comparators are used to compare two objects. In this challenge, you’ll create a comparator and use it to sort an array.
The Player class is provided for you in your editor. It has fields: a String and a integer.
Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.
Sample Input
|
|
Sample Output
|
|
代码如下:
|
|
知识点补充:
- String类有个compareTo()函数,前者比后者小时返回负数。
public int compare(Player p1, Player p2)
返回负数时,不换位置。- 注意用法:
Arrays.sort(player, checker);
原题链接:Java Sort
You are given a list of student information: ID, FirstName, and CGPA. Your task is to rearrange them according to their CGPA in decreasing order. If two student have the same CGPA, then arrange them according to their first name in alphabetical order. If those two students also have the same first name, then order them according to their ID. No two students have the same ID.
Sample Input
|
|
Sample Output
|
|
代码如下:
|
|
知识点补充:
这题用了容器ArrayList,所以重写好Comparator接口后,排序时要用Collections.sort(studentList, new StudentComparator());