compare and sort different type of objects using java Collections

倖福魔咒の 提交于 2019-12-18 08:23:16

问题


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


回答1:


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
    }
}

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
    }
}

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


Resources :

  • Javadoc - Collections.sort()
  • Javadoc - Comparable
  • Javadoc - Comparator



回答2:


The easiest way would involve your classes all implementing an interface or extending a base class that expose the common attribute (lifeTime) used for the comparison. Otherwise, you could just create a Comparator that uses reflection to get the lifeTime attribute and use that value in the compare method for your comparator. Of course, this will throw exceptions if your collection ever contains an object that has no lifeTime attribute.




回答3:


If all your classes implement a Living interface defined as it follows (always a good idea in Java):

public interface Living {
    int getLifeTime();
}

you can sort your collections of Living objects by using the lambdaj library as it follows:

List<Alive> sortedLivings = sort(livings, on(Alive.class).getLifeTime());


来源:https://stackoverflow.com/questions/3845755/compare-and-sort-different-type-of-objects-using-java-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!