public class User implements Comparable{ private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } 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 String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { System.out.println("User equals()...."); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (age != user.age) return false; return name != null ? name.equals(user.name) : user.name == null; } @Override public int hashCode() { //return name.hashCode() + age; int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } //按照姓名从大到小排列,年龄从小到大排列 @Override public int compareTo(Object o) { if(o instanceof User){ User user = (User)o; // return -this.name.compareTo(user.name); int compare = -this.name.compareTo(user.name); if(compare != 0){ return compare; }else{ return Integer.compare(this.age,user.age); } }else{ throw new RuntimeException("输入的类型不匹配"); } } }
方式二:
@Test public void test2(){ Comparator com = new Comparator() { //按照年龄从小到大排列 @Override public int compare(Object o1, Object o2) { if(o1 instanceof User && o2 instanceof User){ User u1 = (User)o1; User u2 = (User)o2; return Integer.compare(u1.getAge(),u2.getAge()); }else{ throw new RuntimeException("输入的数据类型不匹配"); } } }; TreeSet set = new TreeSet(com); set.add(new User("Tom",12)); set.add(new User("Jerry",32)); set.add(new User("Jim",2)); set.add(new User("Mike",65)); set.add(new User("Mary",33)); set.add(new User("Jack",33)); set.add(new User("Jack",56)); Iterator iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } }
package com.collection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * @version v1.0 * @ProjectName: cshjavatest * @ClassName: demo01 * @Description: TODO(一句话描述该类的功能) * @Author: CSH * @Date: 2020/5/31 9:12 */ public class Demo01 { public static void main(String[] args) { Comparator comparator=new Comparator() { @Override public int compare(Object o1, Object o2) { if(o1 instanceof Integer && o2 instanceof Integer){ Integer int1=(Integer) o1; Integer int2=(Integer) o2; // 方式一 // return -Integer.compare(int1,int2); // 方式二 if (int1>int2){ return -1; }else if(int1<int2){ return 1; }else { return 0; } }else { throw new RuntimeException("输入的数据类型不匹配"); } } }; ArrayList arrayList=new ArrayList(); arrayList.add(1); arrayList.add(95); arrayList.add(10); arrayList.add(88); arrayList.add(-8); Collections.sort(arrayList,comparator); System.out.println(arrayList); } }