How to compare objects by multiple fields

后端 未结 22 2576
暖寄归人
暖寄归人 2020-11-22 00:43

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

public class Person {

    private String firstName;
    private String lastN         


        
22条回答
  •  一生所求
    2020-11-22 01:36

    You should implement Comparable . Assuming all fields will not be null (for simplicity sake), that age is an int, and compare ranking is first, last, age, the compareTo method is quite simple:

    public int compareTo(Person other) {
        int i = firstName.compareTo(other.firstName);
        if (i != 0) return i;
    
        i = lastName.compareTo(other.lastName);
        if (i != 0) return i;
    
        return Integer.compare(age, other.age);
    }
    

提交回复
热议问题