[Java開発の道](21)ComparatorとComparable
package java.lang;
import java.util.*;
public interface Comparable<T> {
public int compareTo(T o);
}
:
Comparable 。 Comparable , 。 Comparable List ( ), List ( ) Collections.sort( Arrays.sort) 。
x.compareTo(y) “ x y ”。 “ ”, “x y ”; “ ”, “x y”; “ ”, “x y”。
:
package com.qunar.test;
/**
* Created by xiaosi on 16-3-7.
*/
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = 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;
}
@Override
public int compareTo(Student stu) {
if(age == stu.getAge()){
return name.compareTo(stu.getName());
}//if
else if(age > stu.getAge()){
return 1;
}
return -1;
}
}
List<Student> stus = new ArrayList<Student>();
stus.add(new Student("xiaosi",24));
stus.add(new Student("sunny",24));
stus.add(new Student("yoona",21));
stus.add(new Student("kim",27));
Collections.sort(stus);
for(Student stu : stus){
System.out.println("age" + stu.getAge() + " name->" + stu.getName());
}
: student age , , name 。
2. Comparator
package java.util;
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
:
, Comparable 。 。 Comparator 。 , 。
:
package com.qunar.test;
/**
* Created by xiaosi on 16-3-7.
*/
public class Teacher {
private String name;
private int age;
public Teacher(String name, int age) {
this.name = name;
this.age = 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;
}
}
:
package com.qunar.test;
import java.util.Comparator;
/**
* Created by xiaosi on 16-3-7.
* Teacher
*/
public class TeacherComparator implements Comparator<Teacher>{
@Override
public int compare(Teacher o1, Teacher o2) {
if(o1.getAge() == o2.getAge()){
return o1.getName().compareTo(o2.getName());
}//if
else if(o1.getAge() > o2.getAge()){
return 1;
}
return -1;
}
}
List<Teacher> teachers = new ArrayList<Teacher>();
teachers.add(new Teacher("xiaosi",24));
teachers.add(new Teacher("sunny",24));
teachers.add(new Teacher("yoona",21));
teachers.add(new Teacher("kim",27));
Collections.sort(teachers,new TeacherComparator());
for(Teacher te : teachers){
System.out.println("age" + te.getAge() + " name->" + te.getName());
}
3.
Comparable ( String、Integer )。 Comparator , , 。 , 。
Comparator (strategy design pattern), , (strategy object) 。 : ,Integer , Integer ( ) , Comparator 。
Comparable : , , ,
Comparator : ,