Jav*_*ser 5 java sorting collections
如何使用java Collections比较和排序不同类型的对象.Below是用例:例如DOG,MAN,TREE,COMPUTER,MACHINE - 所有这些不同的对象都有一个共同的属性,如"int lifeTime".现在我想根据lifeTime属性来命令这些对象
谢谢
所有这些对象都应该有一个共同的抽象类/接口,比如Alive一个方法getLifeTime(),你可以Alive扩展Comparable<Alive>或创建自己的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
}
}
Run Code Online (Sandbox Code Playgroud)
要么
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
}
}
Run Code Online (Sandbox Code Playgroud)
在此之后,下一个步骤是使用任一种自动排序集合(TreeSet<Alive>)或排序一个List<Alive>用Collections.sort().
资源:
| 归档时间: |
|
| 查看次数: |
3233 次 |
| 最近记录: |