Sorting a List alphabetically using compareTo() method

前端 未结 4 1076
星月不相逢
星月不相逢 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 09:01

    You can make your Person class implement Comparable, and define the following method:

        public class Person implements Comparable {
    
           // Your previous code
    
           public int compareTo(Person other) {
              if (other == null) {
                 // throw exception for example
              }
              return this.name.toLowerCase().compareTo(other.name.toLowerCase());
           }
        }
    

提交回复
热议问题