Calvin Kaiser
Calvin Kaiser

Reputation: 33

Collections.sort isn't working

public void sortByLastName(){
    Collections.sort(list, new Comparator<Person>() {
        public int compare(Person p1, Person p2){
            return p1.getLastName().compareTo(p2.getLastName());
        }
    } );
}

The code shown here is part of a contactList array where i'm sorting out the list by last name, I can't seem to get it to compile, and I don't see what's wrong.

EDIT: The error on the compiler is

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Person[], new Comparator<Person>(){})
at ContactList.sortByLastName(ContactList.java:34)
at Main.main(Main.java:18)

Upvotes: 1

Views: 959

Answers (2)

Rob G
Rob G

Reputation: 3526

Because your list is an array, you're going to want to sort using Arrays.sort rather than Collections.sort.

Upvotes: 0

Todd
Todd

Reputation: 31720

sort(List, Comparator) in the type Collections is not applicable for the arguments (Person[], new Comparator(){})

This is telling you that the method Collections.sort(), which takes a List and a Comparator doesn't match what you are handing in, which seems to be an array of Person objects (Person[]) and a Comparator. Arrays and Lists in Java may seem similar at first, but they are different. In order to sort an array of objects, use Arrays.sort() instead.

Upvotes: 1

Related Questions