【Java】Comparable & Comparator 自定义排序

自定义排序两种方式

  • 实现Comparable接口,并重写compareTo方法
  • 实现Comparator接口,并重写compare方法

Collections工具类

sort方法

  • sort(List
  • sort(List, comparator)

自己实现一个Collections类(MySort)

package compare;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
 * 排序实现,对数组
 * @author 袁盛桐
 *
 */
public class MySort {
	
	/**
	 * 数组排序+comparator接口
	 * @param 
	 */
	public static void sort(String[] arr, MyComparator com) {
		boolean sorted = true;
		int len = arr.length;
		//趟数
		for(int j =0; j < len-1; j++) {
			//假定有序
			sorted = true;
			for(int i =0; i> void sort(List arr) {
		//第一步:转成数组
		Object[] arr2 = arr.toArray();
		sort(arr2);
		//第二部:改变容器中对应的值
		for(int i =0; i> void sort(T[] arr) {
		boolean sorted = true;
		int len = arr.length;
		//趟数
		for(int j =0; j < len-1; j++) {
			//假定有序
			sorted = true;
			for(int i =0; i list = new ArrayList();
		list.add("a");
		list.add("abcd");
		list.add("abc");
		list.add("def");
		MySort.sort(list);
		System.out.println(list);
		
		System.out.println("使用comparator排序");
		String[] arr3 = new String[] {"a","abcd","abc","def"};
		MySort.sort(arr3,new MyComparator());
		for(String x:arr3) {
			System.out.println(x);
		}
	}
}

 自定义类Newsletter测试,并用Comparable接口实现自定义排序功能

定义一个NewsletterSort类,并重写compareTo方法,在main中, 直接调用collections类中的sort方法,并传入list,这时候执行的sort方法为newsletter自定义的sort方法,sort方法按照自己的业务逻辑进行重写。

package compare;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 实现接口comparable方式排序
 * @author 袁盛桐
 *
 */
public class NewsletterSort implements java.lang.Comparable{
	//标题
	private String title;
	//点击量
	private int hits;
	//时间
	private Date Pubtime;
	
	public NewsletterSort() {
		
	}

	public NewsletterSort(String title, int hits, Date pubtime) {
		super();
		this.title = title;
		this.hits = hits;
		Pubtime = pubtime;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getHits() {
		return hits;
	}

	public void setHits(int hits) {
		this.hits = hits;
	}

	public Date getPubtime() {
		return Pubtime;
	}

	public void setPubtime(Date pubtime) {
		Pubtime = pubtime;
	}
	
	//按时间降序+点击量升序+标题降序业务逻辑
	@Override
	public int compareTo(NewsletterSort o) {
		int result= 0;
		//比较时间降序
		result = -this.Pubtime.compareTo(o.Pubtime);
		if(result == 0) {//时间相同
			//看点击量
			result = this.hits-o.hits;
			if(result == 0) {//点击量相同
				//标题
				result = -this.title.compareTo(o.title);
			}
		}
		
		return result;
	}
	
	//重写tostring方法
	@Override
	public String toString() {
		StringBuilder x = new StringBuilder();
		x.append("标题:").append(this.title);
		x.append(",时间:").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.Pubtime));
		x.append(",点击量:").append(this.hits).append("\n");
		return x.toString();
	}
	
	public static void main(String[] args) {
		List news = new ArrayList();
		news.add(new NewsletterSort("标题长度为111111111111111",100, new Date(System.currentTimeMillis()-5000*60*60)));
		news.add(new NewsletterSort("标题长度为222222222222",50, new Date(System.currentTimeMillis()-1000*60*60)));
		news.add(new NewsletterSort("标题长度为3333333",30, new Date(System.currentTimeMillis()-1000*60*60)));
		System.out.println("排序前"+news);
		MySort mySort = new MySort();
		mySort.sort(news);
		System.out.println("排序后"+news);
		
	}
}

自定义类Goods测试,并用Comparator接口实现自定义排序功能

自定义GoodsSort类,自定义根据自己业务逻辑实现的排序类,实现comparator接口中的compare方法

与comparable方法不同的是,在调用collections.sort方法时,除了传入list外,传入第二个参数排序类,这样做实现了排序方法与实体类解耦的目的,修改时只需修改排序类即可。

package Goods_comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GoodsSort {
	//商品名
	private String name;
	//价格
	private double price;
	//收藏量
	private double favorate;
	
	public GoodsSort() {
		
	}
	
	public GoodsSort(String name, double price, double favorate) {
		super();
		this.name = name;
		this.price = price;
		this.favorate = favorate;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public double getFavorate() {
		return favorate;
	}

	public void setFavorate(double favorate) {
		this.favorate = favorate;
	}
	
	@Override
	public String toString() {
		return "商品名:"+name+",收藏量:"+favorate+",价格:"+price+"\n";
	}
	
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(new GoodsSort("goodslong111111111",100,2000));
		list.add(new GoodsSort("goodsmiddle2222",300,1000));
		list.add(new GoodsSort("goodsshort333",50,7000));
		
		System.out.println("排序前"+list);
		//传入list和排序类,排序类实现comparator接口,实现解耦的目的
		Collections.sort(list, new GoodsPriceCompare());
		System.out.println("排序后"+list);
	}
	
}
package Goods_comparator;

/**
 * 对Goods按价格降序排序的业务类
 * 实现comparator接口方式排序
 * @author 袁盛桐
 *
 */
public class GoodsPriceCompare implements java.util.Comparator {

	@Override
	public int compare(GoodsSort o1, GoodsSort o2) {
		return -(o1.getPrice()-o2.getPrice()>0?1:(o1.getPrice()==o2.getPrice()?0:-1));
		
	}
	

}

 

你可能感兴趣的:(java)