import java.util.ArrayList;
import java.util.Collections;
public class Person implements Comparable<Person>{
private String name;
private int age;
private String sex;
public Person(String name ,int age, String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
//重写equals方法
public boolean equals(Object other) {
boolean flag = false;
if(other == null) {
return flag;
}
if(this == other) {
return !flag;
}
if (other instanceof Person) {
Person p = (Person)other;
if(!this.name.equals(p.name)) {
return flag;
}
if(this.age != p.age) {
return flag;
}
if(!this.sex.equals(p.sex)) {
return flag;
}
flag = true;
}
return flag;
}
//重写hasCode
public int hashCode() {
return this.name.hashCode();
}
//实现compareTo接口,首先按age排序,再按name排序
public int compareTo(Person p) {
if(this.age > p.age){
return 1;
}else if(this.age < p.age) {
return -1;
}else{
return this.name.compareTo(p.name);
}
}
public static void main(String[] args) {
Person p1 = new Person("TOM",10,"male");
Person p2 = new Person("Mary",12,"female");
Person p3 = new Person("TOM",10,"male");
Person p4 = new Person("Ryan",9,"male");
Person p5 = new Person("Aill",9,"male");
Person p6 = new Person("Cindy",12,"female");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
System.out.println(p1.equals(p3));//true;
System.out.println(p1.equals(p2));//false;
Collections.sort(list);
for (Person p : list) {
System.out.println(p.name + " " + p.age + " " + p.sex);
}
/*打印结果
Aill 9 male
Ryan 9 male
TOM 10 male
Cindy 12 female
Mary 12 female
*/
}
}