如何使用java集合比较和排序不同类型的对象.Below是用例:例如DOG,MAN,TREE,COMPUTER,MACHINE - 所有这些不同的对象有一个公共属性说int lifeTime 。现在我想根据lifeTime属性订购这些对象。
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
推荐答案所有这些对象应该有一个公共的抽象类/接口,例如 getLifeTime() Alive ,您可以有 Alive extends Comparable< Alive> 或创建您自己的 Comparator< Alive> 。
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<Alive> or create your own Comparator<Alive>.
public abstract class Alive extends Comparable<Alive>{ public abstract int getLifeTime(); public int compareTo(Alive alive){ return 0; // Or a negative number or a positive one based on the getLifeTime() method } }b $ b
或
Or
public interface Alive { int getLifeTime(); } public class AliveComparator implements Comparator<Alive>{ public int compare(Alive alive1, Alive alive2){ return 0; // Or a negative number or a positive one based on the getLifeTime() method } }b $ b
之后,下一步是使用自动排序的集合( TreeSet< Alive> )或者排序 List< Alive> ; 与 Collections.sort()。
资源:
- Javadoc - Collections.sort()
- a href =download.oracle/javase/6/docs/api/java/lang/Comparable.html> Javadoc - 可比较
- Javadoc - 比较器
- Javadoc - Collections.sort()
- Javadoc - Comparable
- Javadoc - Comparator
更多推荐
使用java集合比较和排序不同类型的对象
发布评论