Sorting a List alphabetically using compareTo() method

前端 未结 4 1090
星月不相逢
星月不相逢 2021-01-18 08:37

I am writing a phonebook program in java and i need to list people in the list alphabetically and to do that i need to write a sorting algorithm for a list in java and it sh

4条回答
  •  半阙折子戏
    2021-01-18 08:59

    As everyone else has mentioned, compareTo is part of the Comparable interface.

    How you implement it depends on whether you want to order by surname or name first and if you want them sorted ascending order.

    For example, if you want to order by surname first, in ascending order:

    public class Person implements Comparable {
        // the parts of Person you already have would go here
        public int compareTo(Person person) {
            if (person == null) {
                return -1;
            }
    
            if (surname != null && person.getSur() == null) {
                return -1;
            } else if (surname == null && person.getSur() != null) {
                return 1;
            } else if (surname != null && person.getSur() != null) {
                int compare = surname.compareToIgnoreCase(person.getSur());
                if (compare != 0) {
                    return compare;
                }
            }
            // Note that we did nothing if both surnames were null or equal
    
            if (name == null && person.getName() == null) {
                return 0;
            } else if (name != null && person.getName() == null) {
                return -1;
            } else if (name == null && person.getName() != null) {
                return 1;
            } else {
                return name.compareToIgnoreCase(person.getName());
            }
        }
    }
    

    (I didn't actually test this code)

    This relies on String's implementation of compareToIgnoreCase.

    Note that this also moves all null objects and objects with null names and surnames to the end of the list.

    Having said all that, if you implement Comparable, you can make the Collections API do the work for you using sort.

    If you find that you need multiple different sort methods for an object, you can create a set of Comparator objects to do the sorting instead.

提交回复
热议问题