我在JAVA中有两节课:
public class Persons implements Serializable{
String name;
String phone;
...
}
和
public class Diary implements Comparable{
ArrayList<Persons> persons=new ArrayList();
...
}
我想按名称(按字母顺序)命令我的ArrayList,但我不能使用Collections.sort(),因为我的ArrayList是Persons类,这给了我和错误。我无法在类Persons中实现Comparable,因为如果我这样做,我将无法读取我保存在Object中的ArrayList .dat
答案 0 :(得分:2)
试试这个
Collections.sort(persons, new Comparator<Persons>() {
@Override
public int compare(Persons o1, Persons o2) {
return o1.name.compareTo(o2.name);
}});
答案 1 :(得分:0)
如果你想要一个有序的人群,我会这样做。
class Dairy {
final SortedMap<String, Person> people = new TreeMap<String, Person>();
}
或
class Dairy {
final SortedSet<Person> people = new TreeSet<Person>(new MyNameComparator());
}
或
class Dairy {
final List<Person> people = new ArrayList<Person>();
public void sortPeople() {
Collections.sort(people, new MyNameComparartor());
}
}
答案 2 :(得分:0)
以下是您的问题的完整示例..将以下代码保存在Test.java文件中并运行它..
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person implements Serializable{
private static final long serialVersionUID = 1L;
String name ;
String phone ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Person(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return "Person [name=" + name + ", phone=" + phone + "]";
}
}
class Diary {
ArrayList<Person> list = new ArrayList<Person>();
public ArrayList<Person> getList() {
return list;
}
public void setList(ArrayList<Person> list) {
this.list = list;
}
public Diary(ArrayList<Person> list) {
super();
this.list = list;
}
}
public class Test
{
public static void main(String[] args) {
Person p1 = new Person("John","123");
Person p2 = new Person("Aby","456");
Person p3 = new Person("Debra","789");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
Diary d = new Diary(list);
Collections.sort(d.getList(), new Comparator<Person>(){
public int compare(Person item1, Person item2){
int compare = item1.getName().compareTo(item2.getName());
return compare;
}
});
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
使用比较器在日记中对人员列表进行排序而不触及你的人类......