本文介绍了使用java集合比较和排序不同类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如何使用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 或Orpublic 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 =http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html> Javadoc - 可比较 Javadoc - 比较器Javadoc - Collections.sort()Javadoc - ComparableJavadoc - Comparator 这篇关于使用java集合比较和排序不同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 11:15