java sort list of objects by specifiable attribute

前端 未结 4 2009
南方客
南方客 2020-12-07 03:58

I want to sort a List of objects by a specified attribute of those objects and I want to choose which attribute should be used for sorting. Example:

class          


        
4条回答
  •  伪装坚强ぢ
    2020-12-07 04:06

    I think the solution would be more efficient if you passed a Comparator implementation to the Arrays.sort. Right now, you are looping n*2 from the looks of it, the hash map (O(1)) plus the Arrays.sort (which is another 0(n log n) or such). If you do the below, you could skip the 2 loops, and the map, you are using currently.

    You can simply create a Comparator like (rough code):

    class CarComparator implements Comparator {
        enum compareType; //plus setter
    
        public int compareTo(Car a, Car b) {
            if(compareType == COLOUR) return a.colour.compareTo(b.colour);
            if(compareType == NAME.....
        }
    }
    

    , and then simply send the array of Cars to

    Arrays.sort(cars, new CarComparator(COLOUR))
    

    , or use more specialised comparator classes, one for each attribute, and a factory to render them, and of course don't create a new Comparator() for each sort if this is happening often. :-)

    Overall, this approach should make your code more efficient. }

提交回复
热议问题