ArrayList集合之使用与排序之实现:
ArrayList构造函数参数不能传递 比较器对象;
ArrayList自身也不具备比较能力;
如果想对ArrayList中的元素进行比较,需要使用Collections中的sort方法来处理。
public static <T extends Comparable<? super T>> void sort(List<T> list)
针对这种方式,方法中一个参数就是ArrayList集合,但是需要集合的元素,实现Comparable接口中的compareTo方法,使集合中的元素具备比较特性,才能实现比较功能。
public static <T> void sort(List<T> list, Comparator<? super T> c)
针对这种方式,方法中两个参数,其中一个比较器对象,就是说,需要针对集合中的元素来实现比较器,也就是实现接口Comparator中的方法compare。请参考如下代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ArrayListSummarize {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
encapsulationStudent();
}
public static void encapsulationStudent()
{
ArrayList<Student> arrayList = new ArrayList<Student>();
Student student1 = new Student("yunfeng", "20120308", 30);
Student student2 = new Student("lidawei", "20120302", 22);
Student student5 = new Student("zhangsan", "20120309", 22);
Student student3 = new Student("zhuzhiqing", "20120307", 28);
Student student4 = new Student("liuadou", "20120305", 3);
arrayList.add(student1);
arrayList.add(student2);
arrayList.add(student3);
arrayList.add(student4);
arrayList.add(student5);
System.out.println(arrayList);
/*
* 以学号来比较
*/
Collections.sort(arrayList);
System.out.println(arrayList);
/*
* 以年龄来比较
*/
Collections.sort(arrayList, new StudentComparator());
System.out.println(arrayList);
}
}
class StudentComparator implements Comparator<Student>
{
@Override
public int compare(Student student1, Student student2) {
// TODO Auto-generated method stub
int compareResult = new Integer(student1.getAge()).compareTo(new Integer(student2.getAge()));
if(compareResult == 0)
{
return student1.getName().compareTo(student2.getName());
}
return compareResult;
}
}
class Student extends Person implements Comparable<Student>
{
private String studentId;
public Student(String name, String studentId, int age)
{
super(name, age);
this.studentId = studentId;
}
/*
* 按学号来排序
*/
@Override
public int compareTo(Student student)
{
int num = this.getStudentId().compareTo(student.getStudentId());
if(num == 0)
{
return this.getName().compareTo(student.getName());
}
return num;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String toString()
{
return this.getName() + "::" +studentId +"::"+ this.getAge() ;
}
}
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString()
{
return name+ "..." + age;
}
}