012_Comparable和Comparator实例
生活随笔
收集整理的這篇文章主要介紹了
012_Comparable和Comparator实例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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容器泛型比較器, 帶業(yè)務(wù)排序功能, 升序排序* @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;// 趟數(shù)for(int i = 0; i < length - 1; i++) {sorted = true;// 次數(shù)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) { // 減少趟數(shù)break;}}for(int i = 0; i < array.length; i++) {list.set(i, (T)array[i]);}}/*** 數(shù)組泛型比較器, 升序排序* @param array*/public static <T extends Comparable<T>> void sort(T[] array) {sort(array, null);}/*** 數(shù)組泛型比較器, 帶業(yè)務(wù)排序功能, 升序排序* @param array*/@SuppressWarnings("unchecked")public static <T> void sort(T[] array, Comparator<T> c) {int length = array.length;boolean sorted;// 趟數(shù)for(int i = 0; i < length - 1; i++) {sorted = true;// 次數(shù)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) { // 減少趟數(shù)break;}}}}2. 使用SortUtil類
import java.util.Comparator; import java.util.Date;public class UseMySortUtil {public static void main(String[] args) {} }/*** 實(shí)現(xiàn)Comparator接口的,新聞條目安時(shí)間排序的業(yè)務(wù)類 */ class NewsTime implements Comparator<NewItem>{public int compare(NewItem o1, NewItem o2) {return o2.time.compareTo(o1.time);} }/*** 實(shí)現(xiàn)Comparable接口的新聞?lì)?/ 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;// 時(shí)間倒序if((result = o.time.compareTo(time)) == 0) {// 點(diǎn)擊次數(shù)倒序if((result = (o.hits - hits)) ==0) {// 標(biāo)題正序result = title.compareTo(o.title);}}return result;}public String toString() {return "[title = " + title + " hits = " + hits + " time = " + time + "]";}}?
總結(jié)
以上是生活随笔為你收集整理的012_Comparable和Comparator实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 011_TreeMap对键实现了Comp
- 下一篇: 013_JDK的Collections类