2010-12-23 87 views
3

嗨,我选一个的ArrayList如下(是的,我已经进口的使用率)时碰到一个问题:爪哇 - 无法找到符号(ArrayList的排序集合)

Collections.sort(personer); 

我有这样的名单:

private List<Person> personer; 

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

但我得到的错误:

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

回答

4

我回答你在其他职位java - alphabetical order (list)

我相信如果你这样做,将解决你的问题。

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

目前正处在Collections 2种sort方法。你可以使Person实现Comparable接口,或者将比较器作为第二个参数提供给sort
否则,JVM无法知道哪个对象比另一个“更大”或“更小”。

See the docs for details.

所以,选项1

class Person implements Comparable { 
    ... 
} 

Collections.sort(list); 

和选项2

Collections.sort(list, myCustomComparator); 
2

你应该实现Comparable <T> Interface