Comparable
package com.qunar.basicJava.javase.p11CommonlyUsedClass;import java.util.Arrays;/*** Author: libin.chen@qunar.com Date: 14-5-21 19:59*/
class Student implements Comparable<Student> { // 指定泛型类型private String name;private int age;private float score;Student(String name, int age, float score) {this.name = name;this.age = age;this.score = score;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", score=" + score +'}';}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 class ComparableDemo01 {public static void main(String[] args) {Student stu[] = {new Student("张三", 20, 90.0f), new Student("李四", 22, 90.0f), new Student("王五", 20, 99.0f)};Arrays.sort(stu);for (int i = 0; i < stu.length; i++) {System.out.println(stu[i]);}}
}
Comparator 数组排序之二,类似于 C/C++ 的方法,在 java 中叫做补救措施
Student 类
package com.qunar.basicJava.javase.p11CommonlyUsedClass.Comparator;/*** Author: libin.chen@qunar.com Date: 14-5-21 21:32*/
public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (!(obj instanceof Student)) {return false;}Student stu = (Student)obj;if (stu.name.equals(this.name) && stu.age == this.age) {return true;} else {return false;}}public String toString() {return name + "\t\t" + 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;}
}
StudentComparator 类
package com.qunar.basicJava.javase.p11CommonlyUsedClass.Comparator;import java.util.Comparator;
/*** Author: libin.chen@qunar.com Date: 14-5-21 21:40*/
public class StudentComparator implements Comparator<Student> {public int compare(Student s1, Student s2) {if (s1.equals(s2)) {return 0;} else if (s1.getAge() < s2.getAge()) {return 1;} else {return -1;}}
}
ComparatorDemo 主函数,main 例子
package com.qunar.basicJava.javase.p11CommonlyUsedClass.Comparator;import java.util.Arrays;/*** Author: libin.chen@qunar.com Date: 14-5-21 21:38*/
public class ComparatorDemo {public static void main(String[] args) {Student stu[] = {new Student("张三", 30), new Student("李四", 14), new Student("王五", 18)};Arrays.sort(stu, new StudentComparator());for (Student student : stu) {System.out.println(student);}}
}