使用java集合比较和排序不同类型的对象

编程入门 行业动态 更新时间:2024-10-28 10:35:35
本文介绍了使用java集合比较和排序不同类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用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

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

b $ b

之后,下一步是使用自动排序的集合( TreeSet< Alive> )或者排序 List< Alive> ; 与 Collections.sort()。

资源:

  • Javadoc - Collections.sort()
  • a href =download.oracle/javase/6/docs/api/java/lang/Comparable.html> Javadoc - 可比较
  • Javadoc - 比较器
  • Javadoc - Collections.sort()
  • Javadoc - Comparable
  • Javadoc - Comparator

更多推荐

使用java集合比较和排序不同类型的对象

本文发布于:2023-11-29 01:12:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644691.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不同类型   对象   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!