【发布时间】:2011-01-07 03:04:26
【问题描述】:
您将如何按字母或数字对ArrayList 进行排序?我不太确定按字母顺序或数字顺序对数组进行排序的方法将如何工作。
谢谢!
【问题讨论】:
-
完全不清楚您在寻找什么。请详细说明。举例说明问题
您将如何按字母或数字对ArrayList 进行排序?我不太确定按字母顺序或数字顺序对数组进行排序的方法将如何工作。
谢谢!
【问题讨论】:
[Collections.sort][1] 将默认排序。这对于字符串是词汇(字母),对于数字数据类型是数字。如果您需要非标准排序,也可以指定自己的比较器。
例如:
ArrayList list = new ArrayList();
list.add(1);
list.add(10);
list.add(-1);
list.add(5);
Collections.sort( list );
[1]:http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,java.util.Comparator)
【讨论】:
Collections.sort 方法允许使用实现特定排序方法(例如字母或数字排序)的 Comparator 对列表进行排序。
【讨论】:
Collections.sort(list,new Comparator() {
int compare(T o1, T o2) {
// implement your own logic here
}
boolean equals(Object obj) {
// implement your own logic here
}
}
【讨论】:
一般使用Collections.sort()方法对简单的数组列表进行排序。
这是一个例子。
首先实现Comparable接口,然后重写compareTo方法。
public class Student implements Comparable {
private String studentname;
private int rollno;
private int studentage;
public Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
@Override
public int compareTo(Student comparestu) {
int compareage=((Student)comparestu).getStudentage();
}
@Override
public String toString() {
return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
}
}
现在我们可以很好地在 ArrayList 上调用Collections.sort
import java.util.*;
public class ArrayListSorting {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(100, "Nuwan", 19));
arraylist.add(new Student(200, "Kamal", 18));
arraylist.add(new Student(205, "Sunil", 20));
Collections.sort(arraylist);
for(Student str: arraylist){
System.out.println(str);
}
}
}
【讨论】: