首页 > 代码库 > java策略模式,Comparator
java策略模式,Comparator
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()); } } }
本文出自 “matengbing” 博客,请务必保留此出处http://matengbing.blog.51cto.com/11395502/1879008
java策略模式,Comparator
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。