012_Comparable和Comparator实例

本文介绍了一个自定义的排序工具类SortUtil的实现方法,该工具类支持List和数组的升序排序,并且可以接受Comparator接口实例进行业务定制化的排序。通过具体的代码示例展示了如何使用SortUtil进行新闻条目的时间排序。

1. 自定义SortUtil类

import java.util.Comparator;
import java.util.List;

public class SortUtil {
	/**
	 * List容器泛型比较器, 升序排序
	 * @param array
	 */
	public static <T extends Comparable<T>> void sort(List<T> list) {
		sort(list, null);
	}
	
	/**
	 * List容器泛型比较器, 带业务排序功能, 升序排序
	 * @param array
	 */
	@SuppressWarnings({ "unchecked" })
	public static <T> void sort(List<T> list, Comparator<T> c){
		Object[] array = list.toArray();
		int length = array.length;
		boolean sorted;
		// 趟数
		for(int i = 0; i < length - 1; i++) {
			sorted = true;
			// 次数
			for(int j = 0; j < length - i - 1; j++) {
				if((c != null && ((Comparator<Object>)c).compare(array[j], array[j + 1]) > 0) || (c == null && ((Comparable<Object>)array[j]).compareTo(array[j + 1]) > 0)) {
					Object temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
					sorted = false;
				}
			}
			
			if(sorted) { // 减少趟数
				break;
			}
		}
		
		for(int i = 0; i < array.length; i++) {
			list.set(i, (T)array[i]);
		}
	}
	
	/**
	 * 数组泛型比较器, 升序排序
	 * @param array
	 */
	public static <T extends Comparable<T>> void sort(T[] array) {
		sort(array, null);
	}
	
	/**
	 * 数组泛型比较器, 带业务排序功能, 升序排序
	 * @param array
	 */
	@SuppressWarnings("unchecked")
	public static <T> void sort(T[] array, Comparator<T> c) {
		int length = array.length;
		boolean sorted;
		// 趟数
		for(int i = 0; i < length - 1; i++) {
			sorted = true;
			// 次数
			for(int j = 0 ; j < length - i - 1; j++) {
				if((c != null && (c.compare(array[j], array[j + 1]) > 0)) || (c == null && ((Comparable<T>)array[j]).compareTo(array[j + 1]) > 0)) {
					T temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
					sorted = false;
				}
			}
			
			if(sorted) { // 减少趟数
				break;
			}
		}
	}
	
}

2. 使用SortUtil类

import java.util.Comparator;
import java.util.Date;

public class UseMySortUtil {
	public static void main(String[] args) {
		
	}
}

/**
 * 实现Comparator接口的,新闻条目安时间排序的业务类 
 */
class NewsTime implements Comparator<NewItem>{
	public int compare(NewItem o1, NewItem o2) {
		return o2.time.compareTo(o1.time);
	}
}

/**
 * 实现Comparable接口的新闻类
 */
class NewItem implements Comparable<NewItem>{
	public String title;
	public int hits;
	public Date time;
	
	public NewItem(String title, int hits, Date time) {
		this.title = title;
		this.hits = hits;
		this.time = time;
	}

	public int compareTo(NewItem o) {
		int result = 0;
		// 时间倒序
		if((result = o.time.compareTo(time)) == 0) {
			// 点击次数倒序
			if((result = (o.hits - hits)) ==0) {
				// 标题正序
				result = title.compareTo(o.title);
			}
		}
		
		return result;
	}
	
	public String toString() {
		return "[title = " + title + " hits = " + hits + " time = " + time + "]";
	}
	
}

 

`Comparable` `Comparator` 都是用来对对象排序的接口,但在使用场景设计意图上有所不同。 ### 1. **Comparable 接口** `Comparable<T>` 是 Java 中的一个泛型接口,它允许你在定义类的时候指定该类的对象应该如何比较大小。通常用于表示自然顺序(natural ordering),例如数字从小到大、字符串按字典序等。 #### 特点: - 类本身需要实现这个接口,并提供 `compareTo(T o)` 方法的具体实现。 - 只能有一种比较规则,即只能有一个“自然”排序方式。 - 如果某个类实现了 `Comparable`,那么它的实例可以直接通过 `Collections.sort()` 或 `Arrays.sort()` 进行排序。 **示例:** ```java public class Person implements Comparable<Person> { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person other) { return Integer.compare(this.age, other.age); // 按年龄升序排列 } } ``` --- ### 2. **Comparator 接口** `Comparator<T>` 同样是一个泛型接口,但它不是由类直接实现的,而是作为外部策略模式来使用的。你可以创建一个独立的 Comparator 实现类或匿名内部类,甚至可以使用 lambda 表达式,在运行时动态地传递给排序算法。 #### 特点: - 提供了更灵活的比较逻辑,可以在不修改原有类的情况下为同一个类提供多种排序方式。 - 可以有多个不同的 `Comparator` 来处理同一种类型的对象的不同排序需求。 - 经常与 `TreeSet`, `PriorityQueue` 等数据结构一起使用,也可以传入 `sort()` 方法中作为参数。 **示例:** ```java import java.util.*; List<Person> people = new ArrayList<>(); // 添加一些Person对象... // 使用Comparator按名字排序 people.sort(Comparator.comparing(person -> person.getName())); // 或者按年龄降序排序 people.sort((p1, p2) -> Integer.compare(p2.getAge(), p1.getAge())); ``` --- ### 总结 - **Comparable**:适合于对象自带的一种天然有序关系,且这种顺序通常是唯一的; - **Comparator**:适用于当你想要在同一组对象上有多种不同的排序方式,或者不想改变原始类的设计时; 选择哪一个取决于具体的业务需求以及你希望如何组织代码。 --
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值