Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
683 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 :


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...