简体   繁体   中英

Collections Sorting in Java

Whats wrong with this sort? It doesn't work properly.

 public List<LibRegistration> getLibraryRegistrationsSortedByTypeAndName()
    {
        List<LibRegistration> l = getLibRegs();
        Collections.sort(l, new Comparator<LibRegistration>() {
            public int compare(LibRegistration o1, LibRegistration o2) {
               return o1.getLibraryType().compareTo(o2.getLibraryType()) != 0?o1.getLibraryType().compareTo(o2.getLibraryType()):o1.getLibraryName().compareTo(o2.getLibraryName());
            }
        });
        return l;
    }

Nothing wrong, more clear:

        public int compare(LibRegistration o1, LibRegistration o2) {
            int cmp = o1.getLibraryType().compareTo(o2.getLibraryType());
            if (cmp == 0)
                cmp = o1.getLibraryName().compareTo(o2.getLibraryName());
            return cmp;
        }

Though nulls not allowed and compareTo well defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM