compare and sort different type of objects using java Collections

前端 未结 3 1577
一生所求
一生所求 2020-12-20 22:55

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

3条回答
  •  被撕碎了的回忆
    2020-12-20 23:53

    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 :

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

提交回复
热议问题