Java比较自定义对象 [英] Java comparing custom objects

查看:190
本文介绍了Java比较自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自定义对象的ArrayList。我需要通过不同的参数来实现排序,即年份和价格的上升和下降。最好的方法是什么?我考虑过实施 Comparator 并传递排序模式在比较器实例化期间构造函数。这是个好主意吗?

I've got ArrayList of custom objects. I need to implement sorting by different parametres, i.e. year and price both ascending and descending. What's the best way to do it? I thought about implementing Comparator and passing sort mode to constructor during instantiation of comparator. Is that good idea?

推荐答案

我建议使用不同的比较器每种排序类型的实现。匿名内部类,枚举和Java SE 8(!),lambdas,是实现 Comparator 和其他无状态函数类对象的好方法。

I would suggest using a different Comparator implementation per sort type. Anonymous inner classes, enums and, in Java SE 8(!), lambdas, are good ways to implement Comparator and other stateless function-like objects.

您可以使用 Collections.reverseOrder

这篇关于Java比较自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆