對(duì)集合元素排序比較
1. 使用 Comparable 接口實(shí)現(xiàn)默認(rèn)排序
Comparable
是 Java 中的一個(gè)接口,用于定義對(duì)象之間的排序規(guī)則。
實(shí)現(xiàn)了 Comparable
接口的類可以比較其對(duì)象的大?。òb類都實(shí)現(xiàn)了該接口),從而可以在集合類(如 TreeSet、TreeMap 等)中進(jìn)行排序和查找操作。這種排序被稱為類的自然排序,類的 compareTo()
方法被稱為它的自然比較方法。
public interface Comparable<T> {
int compareTo(T o);
}
compareTo()
方法的返回值有以下三種情況:
- 返回負(fù)整數(shù):表示當(dāng)前對(duì)象小于傳入對(duì)象。
- 返回零:表示當(dāng)前對(duì)象等于傳入對(duì)象。
- 返回正整數(shù):表示當(dāng)前對(duì)象大于傳入對(duì)象。
-
T
是泛型的一種表現(xiàn)方式,表示一種類型。
示例1
學(xué)生類 Student 實(shí)現(xiàn)了 Comparable 接口,重寫(xiě)了 compareTo()
方法,通過(guò)比較總成績(jī)實(shí)現(xiàn)對(duì)象之間的大小比較。
public class Student implements Comparable{
private String name;
private int math;
private int chinese;
public Student(String name, int math, int chinese) {
this.name = name;
this.math = math;
this.chinese = chinese;
}
public int getMath() {
return math;
}
public int getChinese() {
return chinese;
}
// 獲取總成績(jī)
public int getTotal() {
return math + chinese;
}
// 根據(jù)方法重寫(xiě)比較器
@Override
public int compareTo(Object o) throws RuntimeException {
if (o instanceof Student student) {
if (this.getTotal() > student.getTotal()) {
return 1;
} else if (this.getTotal() < student.getTotal()) {
return -1;
}
// 比較姓名
return this.name.compareTo(student.name);
}
throw new CompareException("類型不匹配");
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", math=" + math +
", chinese=" + chinese +
'}' + getTotal();
}
// 自定義異常
class CompareException extends RuntimeException {
public CompareException() {
super();
}
public CompareException(String message) {
super(message);
}
}
}
public class ComparableExample {
public static void main(String[] args) {
Student[] stus = {
new Student("張三", 23, 90),
new Student("李四", 24, 80),
new Student("王五", 23, 70),
new Student("趙六", 24, 80),
new Student("田七", 25, 50)
};
sort(stus);
for (Student student : stus) {
System.out.println(student.toString());
}
}
private static void sort(Student[] students) {
for (int i = 0; i < students.length - 1; i++) {
for (int j = 0; j < students.length - 1 - i; j++) {
if (students[j].compareTo(students[j + 1]) < 0) {
Student studentTemp = students[j];
students[j] = students[j + 1];
students[j + 1] = studentTemp;
}
}
}
}
}
輸出
Student{name='張三', math=23, chinese=90}113
Student{name='趙六', math=24, chinese=80}104
Student{name='李四', math=24, chinese=80}104
Student{name='王五', math=23, chinese=70}93
Student{name='田七', math=25, chinese=50}75
2. 使用 Comparator 接口實(shí)現(xiàn)比較器排序
Comparator
是 java 中的一個(gè)接口,用于定義對(duì)象之間的定制排序規(guī)則。
與 Comparable
接口不同,Comparator
接口允許在排序時(shí)使用獨(dú)立于對(duì)象類的比較邏輯,因此可以在不休改對(duì)象類的情況下實(shí)現(xiàn)多種不同的排序方式,當(dāng)使用了實(shí)現(xiàn) Comparator
接口的比較器后,默認(rèn)的 COmparable
比較器就不起作用了。
使用 Comparator 接口需要重寫(xiě) compare() 方法,該方法的定義語(yǔ)法格式如下:
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
示例2
按照語(yǔ)文成績(jī)排序
import java.util.Arrays;
import java.util.Objects;
public class ComparableExample {
public static void main(String[] args) {
Student[] stus = {
new Student("張三", 23, 90),
new Student("李四", 24, 80),
new Student("王五", 43, 70),
new Student("趙六", 24, 80),
new Student("田七", 25, 50)
};
// 使用 Arrsys.sort(),傳入比較器,實(shí)現(xiàn)對(duì)多個(gè)對(duì)象比較
ChineseComparator comparator = new ChineseComparator();
Arrays.sort(stus, comparator);
for (Student student : stus) {
System.out.println(student.toString());
}
// 比較兩個(gè)對(duì)象
// int n = Objects.compare(stus[1], stus[3], comparator);
// System.out.println(n);
}
package kfm.bases.SetDemo;
import java.util.Comparator;
public class ChineseComparator implements Comparator {
// 按照語(yǔ)文成績(jī)排序
@Override
public int compare(Object o1, Object o2) {
if (o1 != null && o2 != null) {
if (o1 instanceof Student student1 && o2 instanceof Student student2) {
return student1.getChinese() - student2.getChinese();
} else {
throw new RuntimeException("數(shù)據(jù)類型異常");
}
} else {
throw new RuntimeException("空指針異常");
}
}
}
輸出:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-688268.html
Student{name='田七', math=25, chinese=50}75
Student{name='王五', math=43, chinese=70}113
Student{name='李四', math=24, chinese=80}104
Student{name='趙六', math=24, chinese=80}104
Student{name='張三', math=23, chinese=90}113
compare()
方法用于在 Arrays
類調(diào)用 sort(比較對(duì)象數(shù)組, 比較器)
方法時(shí),對(duì)兩個(gè)對(duì)象進(jìn)行比較大小。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-688268.html
到了這里,關(guān)于Java基礎(chǔ)二十二(對(duì)集合元素排序比較)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!