3

Hi i run into a problem when sorting an arrayList as following (and yes i have imported util):

    Collections.sort(personer);

I have this list:

private List<Person> personer;

public Register() {
    personer = new ArrayList<Person>();
}

But i got the error:

mittscript.java:45: cannot find symbol symbol : method sort(java.util.List) location: class java.util.Collections Collections.sort(personer);

Jake
  • 123
  • 4
  • 6
  • 12

3 Answers3

4

I answered you in your other post java - alphabetical order (list)

I believe if you do it, will fix your problems.

Collection<Person> listPeople = new ArrayList<Person>();

The class Person.java will implements Comparable

public class Person implements Comparable<Person>{

public int compareTo(Person person) {
  if(this.name != null && person.name != null){
   return this.name.compareToIgnoreCase(person.name);
  }
  return 0;
 }

}

Once you have this, in the class you're adding people, when you're done adding, type:

Collections.sort(listPeople);
Community
  • 1
  • 1
Gondim
  • 3,038
  • 8
  • 44
  • 62
2

There're two sort methods in Collections. You can either make Person implement Comparable interface, or provide comparator as a second argument into sort.
Otherwise, there's no way for JVM to know which Person object is 'bigger' or 'smaller' than another.

See the docs for details.

So, option 1

class Person implements Comparable {
    ...
}

Collections.sort(list);

and option 2

Collections.sort(list, myCustomComparator);
Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
2

You should implement Comparable < T > Interface