Graceful Java Programming 之使用Collection排序

本文详细介绍了Java中TreeSet和TreeMap的时间复杂度为log(n),并提供了两种实现方式:一种是通过实现Comparable接口,另一种是通过Comparator接口。此外,还讨论了使用Collections.sort方法对List进行排序的时间复杂度为n*log(n),以及实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.TreeSet 、 TreeMap
时间复杂度: log(n)
方法一: 对存入TreeSet的对象和put到TreeMap的key实现java.util.Comparable接口
代码样例:
[code]
public class TokenDelegate implements Comparable{
//词元的起始位移
private int offset;
//词元的起始位置
private int begin;
//词元的终止位置
private int end;
......
......

/*
* 词元在排序集合中的比较算法
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o){
TokenDelegate ntd = (TokenDelegate)o;
if(this.begin < ntd.begin){
return -1;
}else if (this.begin == ntd.begin){
//当起始位置相同时,长词优先
if( this.end > ntd.end ){
return -1;
}else if(this.end == ntd.end){
return 0;
}else if(this.end < ntd.end){
return 1;
}
}
return 1;
}
......
......
}[/code]

方法二:为对象实现java.util.Comparator,并通过构造函数传给TreeSet或TreeMap
代码样例:[code]
class BusLineNameComparator implements Comparator{
......
......
/**
* 公交线路查询结果排序器
* @param one
* @param other
* @return
*/
public int compare(Object one , Object other){
if(one == other){
return 0;
}
if(one instanceof LBSBusLine && other instanceof LBSBusLine){
LBSBusLine busLineA = (LBSBusLine)one;
LBSBusLine busLineB = (LBSBusLine)other;
String busNameA = busLineA.getName();
String busNameB = busLineB.getName();
//判断是否同一条线路
if(busLineA.equals(busLineB)){
return 0;
}
//判断公交线路名称长度
if(busNameA.length() < busNameB.length()){
return -1;
}else if(busNameA.length() > busNameB.length()){
return 1;
}else{
return busNameA.compareTo(busNameB);
}
}else{
throw new java.lang.ClassCastException("Not LBSBusLine Type.");
}
}
}
......
......
}[/code]
这里要提醒大家注意的是对于TreeSet中的对象和TreeMap的key,判断对象是否相等不是根据对象的equals方法实现的,而是根据对象的compareTo()实现或者比较器Comparator中的compare方法是否返回0来鉴别的,这一点在实现比较器的排序和集合的contain判别中尤为重要。


二.使用java.util.Collections.sort对List排序,其时间复杂度为n*log(n)。

使用java.util.Collections.sort方法同样可以通过对象自身实现Comparable接口,或者为sort方法给定Comparator实现来完成排序.这里不做复述。同TreeSet不同的是,用java.util.Collections.sort对List进行排序允许List中两个元素的compareTo()或compare()方法返回0,既允许概念上两个重复元素的共存于List中。这也符合了数学概念上Set和List的区别。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值