java中比较器,java 比较器的使用

对于一个实现了Comparable接口的对象,该接口只能实现一次。如果在一个集合里面需要使用id排序,而在另外一个集合里需要按名字排序这时就需要在这个集合里面指定比较器。

Comparable接口声明了compareTo(Object o)方法

Comparator 接口声明了compare(Object o1,Object o2)方法

eg:

第一个树集是按照对象默认的id排序,第二个树集由指定的构造器按照name 排序

public class Employee implements Comparable{

private int id;

private String name;

public Employee(int id, String name){

this.id = id;

this.name = name;

}

public boolean equals(Object o){

if (o == null ){

return false;

}

if (this == o){

return true;

}

if(!(o instanceof Employee)){

return false;

}

Employee employee = (Employee)o;

return (this.id == employee.id) && (this.name.equals(employee.name));

}

public int hashCode(){

int result = 17;

result = 37 * result + id;

result = 37 * result + name.hashCode();

return result;

}

public String toString(){

return "id:"+id+",name:"+name+"";

}

public int compareTo(Employee employee){

//升序

return this.id - employee.id;

//降序

//return  employee.id - this.id;

}

public String getName() {

return name;

}

}

/*******************************************************************/

import java.util.SortedSet;

import java.util.TreeSet;

import java.util.Comparator;

public class TreeSetTest {

public static void main(String []args){

//使用的是实现了Compable 接口对象默认的排序方式,按id升序排序

SortedSet treeSet = new TreeSet&

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值