package comparator;
import java.util.Arrays;
public class User implements Comparable<User> {
private String id;
private int age;
public User(String id, int age) {
this.id = id;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int compareTo(User u) {
return this.age - u.getAge();
}
public static void main(String[] args) {
User[] users = new User[] { new User("a", 30), new User("b", 20) };
//源码中可以看到调用了compareTo方法进行比较
Arrays.sort(users);//从小到达排列
//输出 b 20 a 30
for (int i = 0; i < users.length; i++) {
User user = users[i];
System.out.println(user.getId() + " " + user.getAge());
}
}
}
package comparator;
import java.util.Arrays;
import java.util.Comparator;
//强行对某个对象collection进行整体排序的比较函数,
//可以将Comparator传递给Collections.sort或Arrays.sort。
public class ComparatorDemo implements Comparator<String> {
// 如果继承的是Comparator,则compare的两个方法是Object类型的
@Override
public int compare(String o1, String o2) {
// 比较String的大小即可
return toInt(o1) - toInt(o2);
}
private int toInt(String str) {
//String str = (String) str;
str = str.replaceAll("一", "1");
str = str.replaceAll("二", "2");
str = str.replaceAll("三", "3");
return Integer.parseInt(str);
}
public static void main(String[] args) {
String[] array = new String[] { "一二", "三", "二" };
// 查看其源码,可以看到其是通过调用ComparatorDemo的compare方法比较大小的
// 两个参数则为array里面的值
Arrays.sort(array, new ComparatorDemo()); //有小到达排列
//最后输出 二 三 一二
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
//可以尝试下面的方法
//Collections.sort(list, c);
}
}
package comparator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class UserComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
return o1.getAge() - o2.getAge();//默认升序排列
}
public static void main(String[] args) {
User[] users = new User[] { new User("a", 30), new User("b", 20) };
//运用UserComparator的compare方法进行比较
Arrays.sort(users, new UserComparator());
//输出 b 20 a 30
for (int i = 0; i < users.length; i++) {
User user = users[i];
System.out.println(user.getId() + " " + user.getAge());
}
List<User> list = new ArrayList<User>();
list.add(new User("a", 30));
list.add(new User("b", 20));
//内部转化成数组进行比较
Collections.sort(list);//运用User实现的compareTo方法进行比较
//输出 b 20 a 30
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);
System.out.println(user.getId() + " " + user.getAge());
}
List<User> list2 = new ArrayList<User>();
list2.add(new User("a", 30));
list2.add(new User("b", 20));
Collections.sort(list2, new UserComparator());
//输出 b 20 a 30
for (int i = 0; i < list2.size(); i++) {
User user = list2.get(i);
System.out.println(user.getId() + " " + user.getAge());
}
}
}
Java之Comparable,Comparator
最新推荐文章于 2024-06-07 22:13:55 发布