如何通过多个字段比较对象 [英] How to compare objects by multiple fields

查看:224
本文介绍了如何通过多个字段比较对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一些对象有几个字段可以通过以下方式进行比较:

  public class Person {

private String firstName;
private String lastName;
private String age;

/ *构造函数* /

/ *方法* /

}

所以在这个例子中,当你询问:

  a。 compareTo(b)> 0 

您可能会询问一个姓氏是否在b之前,或者如果a比b早,等等...



在不增加不必要的杂乱或开销的情况下,什么是最简单的方式来实现这些对象之间的多重比较?




  • java.lang.Comparable 界面仅允许一个字段进行比较

  • 添加大量比较方法(即 compareByFirstName() compareByAge()等等)在我看来是凌乱的。 / li>


那么最好的方法是什么?

解决方案

您可以编写一个比较两个Person对象的比较类,您可以根据需要检查多个字段。您可以在比较器中放入一个变量,告诉它要比较哪个字段,尽管写多个比较器可能会更简单。


Assume you have some objects which have several fields they can be compared by:

public class Person {

    private String firstName;
    private String lastName;
    private String age;

    /* Constructors */

    /* Methods */

}

So in this example, when you ask if:

a.compareTo(b) > 0

you might be asking if a's last name comes before b's, or if a is older than b, etc...

What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?

  • java.lang.Comparable interface allows comparison by one field only
  • Adding numerous compare methods (i.e. compareByFirstName(), compareByAge(), etc...) is cluttered in my opinion.

So what is the best way to go about this?

解决方案

You can write a comparator class which compares two Person objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.

这篇关于如何通过多个字段比较对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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