java中in tor,Java comparable 和 comprator

排序

在java 中我们对ArraryList 中的数据进行排序;通常可以使用Collections.sort()

如果ArrayList 里面的元素是String 对象;这样使用是没有问题的。

但是如果是我们自己写的对象进行排序;就不能这样使用,大家不妨可以试一下。

那我们要如何才能实现自己添加类的排序功能呢?不妨先来看看sort方法的使用说明

public static> void sort(Listlist)

All elements in the list must implement the Comparable interface.

Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).a negative integer if this instance is less than another;

a positive integer if this instance is greater than another;;

0 if this instance has the same order as another.;

Comparable

如果自己添加的类需要支持排序,我们需要实现Comparable

假如我们需要排序的对象是这样定义的;我们需要根据对象人的姓名进行排序

class Person{

String name;

}那么我们可以实现Comparable 接口来对我们自己添加的类进行比较

class Person implements Comparable{

String Name;

public int compareTo(Person p){

return name.compareTo(p.getName);

}

public String getName(){

return name;

}

}实现了Comparable的对象,我们就可以调用Collections.sort来对我们的数据进行排序了。

Comparator

当然如果我们自己定义的对象只需要通过一种方式比较排序;那么刚才通过类实现Comparable的方法已经满足要求了;

但是如果,我们需要根据不同的属性进行排序,刚才的方法就不行了;

我们再来看看sort的另一个重载函数

public staticvoid sort(Listlist,

Comparator c)

Sorts the specified list according to the order induced by the specified comparator.

All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).意思就是我们可以通过comparator来达到目的

//我们需要根据人的年龄 和 人的身高排序class Person{String name;int age;int height}//创建并实现按年龄排序的 comparator的内部类class AgeCompare implements Comparator{  public int compare(Person p1,Person p2){      return p1.age-p2.age;  }}//创建并实现按身高排序的Comparator内部类class HeightCompare implements Comparator{

public int compare(Person p1,Person p2){

return p1.height-p2.height;

}

}

实例

在gallery 里面,我们需要把图片或者视频按时间分类的时候;我们通常都会对所有对象先进行排序处理

//排序的类

class SmallItem {

Path path;

long dateInMs;

double lat, lng;

int mediaType;}/

/按时间排序,实现comparatorprivate

static class DateComparator implements Comparator{

@Override        public int compare(SmallItem item1, SmallItem item2) {

return -Utils.compare(item1.dateInMs, item2.dateInMs);        }    }//调用sort

private static final ComparatorsDateComparator =new DateComparator();

Collections.sort(items, sDateComparator);

参考

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值