读书人

对对象按对象的某个属性进展排序

发布时间: 2013-03-25 15:43:04 作者: rapoo

对对象按对象的某个属性进行排序
public class Student<T> implements Comparable<T> {

private int age;
private String name;

public Student() {
super();
}

public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int compareTo(Object o) {

if (o == null) {
try {
throw new Exception("该对象为空!");
} catch (Exception e) {
e.printStackTrace();
}
}

if (!(this.getClass().getName().equals(o.getClass().getName()
.toString()))) {
try {
throw new Exception("该对象的类名不一致!");
} catch (Exception e) {
e.printStackTrace();
}
}

if (!(o instanceof Student)) {
try {
throw new Exception("该对象不是Student的实例!");
} catch (Exception e) {
e.printStackTrace();
}
}
Student student = (Student) o;

return this.getAge() - student.getAge();
}
}


对某个对象按照对象的某个属性进行排序,没必要自己写一些方法,进行排序。

利用JDK的Collections的排序方法即可,

1、该对象的实现Comparable<T>接口

2、重写public int compareTo(Object o)方法。

3、测试方法

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student(29, "张三"));
students.add(new Student(28, "张三"));
students.add(new Student(30, "张三"));
students.add(new Student(31, "张三"));
students.add(new Student(24, "张三"));
students.add(new Student(25, "张三"));
students.add(new Student(27, "张三"));
// 进对象集合进行排序
Collections.sort(students);

// 遍历集合
for (Student s : students) {
System.out.println("age:" + s.getAge() + " name:" + s.getName());
}

}

}

读书人网 >编程

热点推荐