List排序的问题

1.对List进行排序可以通过这种方式,实现(implements) Comparable<T>接口

@Override
public int compareTo( T o)
{
if (null == o)
{
return -1;
}

RunningInstancesItemType instance0 = this.instanceInfo;
RunningInstancesItemType instance1 = o.getInstanceInfo();

if (null == instance0 || null == instance1)
{
return -1;
}
else
{
// 按运行时间排序
String launchTime0 = this.getInstanceInfo().getLaunchTime();
String launchTime1 = o.getInstanceInfo().getLaunchTime();
if (!launchTime0.equals(launchTime1))
{
return launchTime1.compareTo(launchTime0);
}
else
{
// 如果运行时间相同,则按Id排序
String instanceId0 = this.getInstanceInfo().getInstanceId();
String instanceId1 = o.getInstanceInfo().getInstanceId();
return instanceId0.compareTo(instanceId1);
}
}
}

@Override
public boolean equals(Object obj)
{
boolean equals;

if (null == obj)
{
equals = false;
}
else if (this == obj)
{
equals = true;
}
else if (this.getClass() != obj.getClass())
{
equals = false;
}
else
{
InstanceBean o = (InstanceBean)obj;
RunningInstancesItemType instance1 = this.instanceInfo;
RunningInstancesItemType instance2 = o.getInstanceInfo();

if (null == instance1 || null == instance2)
{
equals = false;
}
else
{
if (null == instance1.getLaunchTime())
{
equals = false;
}
else
{
equals = instance1.getLaunchTime().equals(instance2.getLaunchTime());
}
}
}

return equals;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((null == this.getInstanceInfo() || null == this.getInstanceInfo().getLaunchTime()) ?
0 : this.getInstanceInfo().getLaunchTime().hashCode());
return result;
}

2.也可以使用TreesSet实现
SortedSet<T> sortedSet = new TreeSet<T>();
List<T> instanceList;
sortedSet.add(***);//此处*为T的实例化
instanceList = new ArrayList<T>(sortedSet);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值