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

前端 未结 17 2090
醉酒成梦
醉酒成梦 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:54

    One of the simple way of using NullSafe Comparator is to use Spring implementation of it, below is one of the simple example to refer :

    public int compare(Object o1, Object o2) {
            ValidationMessage m1 = (ValidationMessage) o1;
            ValidationMessage m2 = (ValidationMessage) o2;
            int c;
            if (m1.getTimestamp() == m2.getTimestamp()) {
                c = NullSafeComparator.NULLS_HIGH.compare(m1.getProperty(), m2.getProperty());
                if (c == 0) {
                    c = m1.getSeverity().compareTo(m2.getSeverity());
                    if (c == 0) {
                        c = m1.getMessage().compareTo(m2.getMessage());
                    }
                }
            }
            else {
                c = (m1.getTimestamp() > m2.getTimestamp()) ? -1 : 1;
            }
            return c;
        }
    

提交回复
热议问题