How to sort an array of objects containing null elements?

后端 未结 5 1820
梦谈多话
梦谈多话 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:08

    You need your own Comparator implementation and check for nulls and return 0

     Arrays.sort(fClasses, new Comparator() {
        @Override
        public int compare(FClass o1, FClass o2) {
            if (o1 == null && o2 == null) {
                return 0;
            }
            if (o1 == null) {
                return 1;
            }
            if (o2 == null) {
                return -1;
            }
            return o1.compareTo(o2);
        }});
    

提交回复
热议问题