作业:假如有若干个类Person对象存在一个List当中,对他们进行排序,分别按照名字、年龄、id进行排序(要有正序与倒序两种排序方式)。假如姓名和年龄都重复,则按照id的升序进行排序。要求使用策略模式进行。
package com.xy3;
import java.util.Comparator;
public interface StrategyOfPeople extends Comparator //People对象的排序策略
{
int compare(Object o1, Object o2);
}
package com.xy3;
public class AscendingOrder implements StrategyOfPeople //对People对象的正序排列
{
public int compare(Object o1, Object o2)
{
People p1 = (People)o1;
People p2 = (People)o2;
if(p1.getName().compareTo(p2.getName()) > 0)
{
return 1;
}
else if(p1.getName().compareTo(p2.getName()) < 0)
{
return -1;
}
if(p1.getAge() > p2.getAge())
{
return 1;
}
else if(p1.getAge() < p2.getAge())
{
return -1;
}
return p1.getId() - p2.getId();
}
}
package com.xy3;
public class DescendingOrder implements StrategyOfPeople //对People对象的倒序排列
{
public int compare(Object o1, Object o2)
{
People p1 = (People)o1;
People p2 = (People)o2;
if(p1.getName().compareTo(p2.getName()) > 0)
{
return -1;
}
else if(p1.getName().compareTo(p2.getName()) < 0)
{
return 1;
}
if(p1.getAge() > p2.getAge())
{
return -1;
}
else if(p1.getAge() < p2.getAge())
{
return 1;
}
return p1.getId() - p2.getId();
}
}
package com.xy3;
public class People
{
private int id;
private String name;
private int age;
public People(String name, int age, int id)
{
this.name = name;
this.age = age;
this.id = id;
}
public int getId()
{
return id;
}
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;
}
}
package com.xy3;
import java.util.ArrayList;
import java.util.Collections;
public class Test1
{
public static void main(String[] args)
{
People p1 = new People("zhangsan", 18, 1);
People p2 = new People("lisi", 18, 2);
People p3 = new People("wangwu", 19, 3);
People p4 = new People("maliu", 20, 4);
People p5 = new People("lisi", 18, 5);
People p6 = new People("maliu", 18, 6);
ArrayList array = new ArrayList();
array.add(p1);
array.add(p2);
array.add(p3);
array.add(p4);
array.add(p5);
array.add(p6);
Collections.sort(array, new AscendingOrder()); //升序排序
for(int i = 0; i < array.size(); i++)
{
String name = ((People)array.get(i)).getName();
int age = ((People)array.get(i)).getAge();
int id = ((People)array.get(i)).getId();
System.out.println(name + ":" + age + ":" + id);
}
System.out.println("--------------------------------");
Collections.sort(array, new DescendingOrder()); //降序排序
for(int i = 0; i < array.size(); i++)
{
String name = ((People)array.get(i)).getName();
int age = ((People)array.get(i)).getAge();
int id = ((People)array.get(i)).getId();
System.out.println(name + ":" + age + ":" + id);
}
}
}