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接口
2、重写public int compareTo(Object o)方法。
3、测试方法
import java.util.ArrayList;