java集合比较对象,使用java集合比较和排序不同类型的对象

How to compare and sort different type of objects using java Collections .Below is the use case:

For example DOG,MAN,TREE, COMPUTER,MACHINE - all these different objects has a common property say "int lifeTime". Now I want to order these obects based on the lifeTime property

Thx

解决方案

All of these objects should have a common abstract class/interface such as Alive with a method getLifeTime(), and you could have either Alive extends Comparable or create your own Comparator.

public abstract class Alive extends Comparable{

public abstract int getLifeTime();

public int compareTo(Alive alive){

return 0; // Or a negative number or a positive one based on the getLifeTime() method

}

}

Or

public interface Alive {

int getLifeTime();

}

public class AliveComparator implements Comparator{

public int compare(Alive alive1, Alive alive2){

return 0; // Or a negative number or a positive one based on the getLifeTime() method

}

}

After that the next step is to use either an automatically sorted collection (TreeSet) or sort a List with Collections.sort().

Resources :

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值