How to compare objects by multiple fields

后端 未结 22 2887
暖寄归人
暖寄归人 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:21

    Usually I override my compareTo() method like this whenever I have to do multilevel sorting.

    public int compareTo(Song o) {
        // TODO Auto-generated method stub
        int comp1 = 10000000*(movie.compareTo(o.movie))+1000*(artist.compareTo(o.artist))+songLength;
        int comp2 = 10000000*(o.movie.compareTo(movie))+1000*(o.artist.compareTo(artist))+o.songLength;
        return comp1-comp2;
    } 
    

    Here first preference is given to movie name then to artist and lastly to songLength. You just have to make sure that those multipliers are distant enough to not cross each other's boundaries.

提交回复
热议问题