package 设计模式.策略模式;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* @deprecated 通过实现Comparator接口实现排序(策略模式)
*
*
* */
public class Person implements Comparator<Person>{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public boolean equals(Object obj) {
Person person=(Person)obj;
if(this.id==person.getId()){
if(this.hashCode()==person.hashCode()){
return true;
}
}
return false;
}
public void setId(int id) {
this.id = id;
}
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 compare(Person o1, Person o2) {
// TODO Auto-generated method stub
o1=(Person)o1;
o2=(Person)o2;
if(o1.getId()<o2.getId()){
return -1;
}else if(o1.getId()==o2.getId()){
if(o1.getName().compareTo(o2.getName())<0){
return -1;
}
else if(o1.getName().compareTo(o2.getName())>0){
return 1;
}else {
return 0;
}
}
return 1;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public static void main(String[] args) {
Person person1=new Person(1, "张三", 21);
Person person2=new Person(2, "王五", 33);
Person person3=new Person(3, "张三", 21);
Person person4=new Person(3, "王五", 21);
List<Person> list=new ArrayList<Person>();
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
Collections.sort(list, new Person());
Iterator<Person> iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().toString());
}
}
}
转载于:https://blog.51cto.com/matengbing/1879008