开发者

java - cannot find symbol (arrayList sort collection)

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(perso开发者_高级运维ner);


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


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


You should implement Comparable < T > Interface

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜