package com.git.base.comparable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* 比较器的使用演示:
* 规则 比较分数 大的在前面 分数相同比较年龄,年龄小的在前面
* 年龄相同,返回相同
* <p>Title: ComparableDemo.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2016</p>
* <p>Company: Sage</p>
* @author 五虎将
* @date 2016年5月18日下午9:23:53
* @version 1.0
*/
public class ComparableDemo {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("王虎", 14, 80));
list.add(new Student("雷虎", 12, 90));
list.add(new Student("风虎", 15, 70));
list.add(new Student("虎", 11, 100));
list.add(new Student("赵虎", 13, 80));
Collections.sort(list,new ComparatorStudent());
for (Student student : list) {
System.out.println(student);
}
Student[] stu = {
new Student("王虎", 14, 80),
new Student("雷虎", 12, 90),
new Student("风虎", 15, 70),
new Student("宋庆虎", 11, 100),
new Student("赵虎", 13, 80)
};
Arrays.sort(stu);
for (Student student : stu) {
//System.err.println(student);
}
}
}
package com.git.base.comparable;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
public class Student implements Comparable<Student>{
public Student(String name,int age,int score) {
this.name = name;
this.age = age;
this.score= score;
}
private String name;
private int age;
private int 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 int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
//比较的逻辑定义
if(this.getScore()>o.getScore()){
return -1; //成绩大的在前面
}else if (this.getScore()<o.getScore()) {
return 1;
}
//都不是 分数相等 比较年龄
if(this.getAge()<o.getAge()){
return -1;
}else if (this.getAge()>o.getAge()) {
return 1;
}
return 0;
}
@Override
public String toString() {
return name +" " + age + " " + score;
}
@Override
public boolean equals(Object obj) {
if(this ==obj){
return true;
}
if(obj instanceof Student){
Student s = (Student)obj;
if(this.getName().equals(s.getName())&&this.getAge()==s.getAge()&&this.getScore()==s.getScore()){
return true;
}
}
return false;
}
}
package com.git.base.comparable;
import java.util.Comparator;
/**
* 比较学生
* <p>Title: ComparatorStudent.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2016</p>
* <p>Company: Sage</p>
* @author 五虎将
* @date 2016年5月19日上午12:01:16
* @version 1.0
*/
public class ComparatorStudent implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if(o1.equals(o2)){
return 0;
}else if (o1.getScore() > o2.getScore()) {
return -1;
}else if (o1.getScore() < o2.getScore()) {
return 1;
}else{
if(o1.getAge()<o2.getAge()){
return -1;
}else if (o1.getAge() > o2.getAge()) {
return 1;
}
}
return 0;
}
}