Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1522
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

11条回答
  •  青春惊慌失措
    2020-11-22 00:55

    You need make your Contact classes implement Comparable, and then implement the compareTo(Contact) method. That way, the Collections.sort will be able to sort them for you. Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'

    For example, if you wanted to sort by name (A to Z), your class would look like this:

    public class Contact implements Comparable {
    
        private String name;
    
        // all the other attributes and methods
    
        public compareTo(Contact other) {
            return this.name.compareTo(other.name);
        }
    }
    

提交回复
热议问题