How to simplify a null-safe compareTo() implementation?

前端 未结 17 2100
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 18:39

    This is my implementation that I use to sort my ArrayList. the null classes are sorted to the last.

    for my case, EntityPhone extends EntityAbstract and my container is List < EntityAbstract>.

    the "compareIfNull()" method is used for null safe sorting. The other methods are for completeness, showing how compareIfNull can be used.

    @Nullable
    private static Integer compareIfNull(EntityPhone ep1, EntityPhone ep2) {
    
        if (ep1 == null || ep2 == null) {
            if (ep1 == ep2) {
                return 0;
            }
            return ep1 == null ? -1 : 1;
        }
        return null;
    }
    
    private static final Comparator AbsComparatorByName = = new Comparator() {
        @Override
        public int compare(EntityAbstract ea1, EntityAbstract ea2) {
    
        //sort type Phone first.
        EntityPhone ep1 = getEntityPhone(ea1);
        EntityPhone ep2 = getEntityPhone(ea2);
    
        //null compare
        Integer x = compareIfNull(ep1, ep2);
        if (x != null) return x;
    
        String name1 = ep1.getName().toUpperCase();
        String name2 = ep2.getName().toUpperCase();
    
        return name1.compareTo(name2);
    }
    }
    
    
    private static EntityPhone getEntityPhone(EntityAbstract ea) { 
        return (ea != null && ea.getClass() == EntityPhone.class) ?
                (EntityPhone) ea : null;
    }
    

提交回复
热议问题