java策略模式,Comparator
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章