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);

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

2

You should implement Comparable < T > Interface

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.