How to sort an array of objects containing null elements?

后端 未结 5 1829
梦谈多话
梦谈多话 2020-11-27 23:24

In my program an array fClasses of fixed length [7] of objects is created, each object is a class FClass that contains 3 Strings, an <

5条回答
  •  误落风尘
    2020-11-28 00:02

    You have to create a Comparator, rather than use a Comparable.

    public class FClassComparator implements Comparator 
    {
        public int compare(FClass left, FClass right) {
            // Swap -1 and 1 here if you want nulls to move to the front.
            if (left == null) return right == null ? 0 : 1;
            if (right == null) return -1;
            // you are now guaranteed that neither left nor right are null.
    
            // I'm assuming avg is int. There is also Double.compare if they aren't.
            return Integer.compare(left.avg, right.avg); 
        }
    }
    

    Then call sort via:

    Arrays.sort(fClassArray, new FClassComparator());
    

提交回复
热议问题