简介
实现一个通用排序工具类,根据用户所选择的排序对象进行排序;例如通过年龄排序、通过工资排序、或者工资相等的情况下使用年龄排序
代码实现
代码结构图:
package cn.test.logan.day08; import java.util.ArrayList; public class SortUtilTest { public static void main(String[] args) { User u1 = new User("001","张三",30,1000); User u2 = new User("002","李四",29,1200); User u3 = new User("003","王五",27,1000); User u4 = new User("004","狗蛋",24,1400); ArrayList<User> list = new ArrayList<>(); list.add(u1); list.add(u2); list.add(u3); list.add(u4); // 根据年龄排序 //SortUtil.sort(list, new AgeCompare()); // 根据工资排序 //SortUtil.sort(list, new SalaryCompare()); // 先根据工资,工资相等则根据年龄 SortUtil.sort(list, new SalaryAgeCompare()); for(User u:list) { System.out.println(u); } } }SortUtilTest.java
package cn.test.logan.day08; import java.util.ArrayList; public class SortUtil { public static void sort(ArrayList<User> uList,Compare com) { for(int i=0;i<uList.size()-1;i++) { for(int j=0;j<uList.size()-1-i;j++) { // 判断大小 boolean res = com.compare(uList.get(j), uList.get(j+1)); if(res) { User tmp = uList.get(j); uList.set(j,uList.get(j+1)); uList.set(j+1, tmp); } } } } }SortUtil.java
package cn.test.logan.day08; public interface Compare { public boolean compare(User u1,User u2); }Compare.java
package cn.test.logan.day08; /** * 定义一个User类 * 包含:ID,姓名,年龄,薪水 * @author QIN * */ public class User { private String id; private String name; private int age; private float salary; public User() { } public User(String id, String name, int age, float salary) { this.id = id; this.name = name; this.age = age; this.salary = salary; } public String getId() { return id; } public void setId(String 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; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } // 定义toString方法 @Override public String toString() { return this.id + "," + this.name + "," + this.age + "," + this.salary; } }User.java
以下三个分别是对年龄、工资、先工资后年龄排序的类
package cn.test.logan.day08; public class AgeCompare implements Compare{ @Override public boolean compare(User u1, User u2) { if(u1.getAge() > u2.getAge()) { return true; } return false; } }AgeCompare .java
package cn.test.logan.day08; public class SalaryCompare implements Compare{ @Override public boolean compare(User u1, User u2) { if(u1.getSalary() > u2.getSalary()) { return true; } return false; } }SalaryCompare.java
package cn.test.logan.day08; public class SalaryAgeCompare implements Compare{ @Override public boolean compare(User u1, User u2) { // 先根据工资排序,如果工资相同再根据年龄排序 if(u1.getSalary() > u2.getSalary()) { return true; } if(u1.getSalary() == u2.getSalary()) { if(u1.getAge() > u2.getAge() ) { return true; } } return false; } }SalaryAgeCompare.java