參考博客:java學習筆記13--比較器(Comparable、Comparator)
在Java代碼中,我們常常會面臨需要對集合進行排序的情況,這種情況下我們需要手動的定義Java比較器,告訴程序兩個對象如何比較大小。
Java中的比較器分為兩種Comparable和Comparator:
- Comparable:實現Comparable接口,並且重寫compareTo(T o)方法
- Comparator:實現Comparator接口,並且重寫compare()和equals()方法
Comparable實現
class Student implements Comparable<Student>{
private String name;
private int age;
private float score;
public Student(String name,int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student stu) { //覆寫compareTo方法實現排序規則的應用
if(this.score>stu.score){
return -1;
}else if(this.score<stu.score){
return 1;
}else{
if(this.age>stu.age){
return 1;
}else if(this.age<stu.age){
return -1;
}else{
return 0;
}
}
}
public String toString(){
return "姓名:"+this.name+", 年齡:"+this.age+", 成績:"+this.score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
public class T {
public static void main(String[] args) throws Exception{
Student stu[] = {new Student("張三",22,80f)
,new Student("李四",23,83f)
,new Student("王五",21,80f)};
Arrays.sort(stu); //進行排序操作
for (int i = 0; i < stu.length; i++) {
Student s = stu[i];
System.out.println(s);
}
}
}
Compartor
package com.itmyhome;
import java.util.Comparator;
public class MyComparator implements Comparator<Student> { //實現比較器
@Override
public int compare(Student stu1, Student stu2) {
// TODO Auto-generated method stub
if(stu1.getAge()>stu2.getAge()){
return 1;
}else if(stu1.getAge()<stu2.getAge()){
return -1;
}else{
return 0;
}
}
}
class Student {
private String name;
private int age;
public Student(String name,int age ){
this.name = name;
this.age = age;
}
public String toString(){
return "姓名:"+this.name+", 年齡:"+this.age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class T {
public static void main(String[] args) throws Exception{
Student stu[] = {new Student("張三",23)
,new Student("李四",26)
,new Student("王五",22)};
Arrays.sort(stu,new MyComparator()); //對象數組進行排序操作
List<Student> list = new ArrayList<Student>();
list.add(new Student("zhangsan",31));
list.add(new Student("lisi",30));
list.add(new Student("wangwu",35));
Collections.sort(list,new MyComparator()); //List集合進行排序操作
for (int i = 0; i < stu.length; i++) {
Student s = stu[i];
System.out.println(s);
}
System.out.println("*********");
for (int i=0;i<list.size();i++){
Student s = list.get(i);
System.out.println(s);
}
}
}