将做工程过程经常用的内容段做个珍藏,如下内容段是关于 java中List对象通用排序算法的内容,希望能对各位朋友有一些好处。
public class Student {
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
工具类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSort<E> {
public void Sort(List<E> list, final String method, final String sort) {
Collections.sort(list, new Comparator<E>() {
public int compare(E a, E b) {
int ret = 0;
try {
Method m1 = a.getClass().getMethod(method, null);
Method m2 = b.getClass().getMethod(method, null);
if (sort != null && "desc".equals(sort)) {
ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a),null).toString());
} else {
ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
}
} catch (NoSuchMethodException ne) {
System.out.println(ne);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return ret;
}
});
}
}
测试类:
import java.util.ArrayList;
public class ListTest {
public static void main(String[] args) {
ArrayList<Student> list= new ArrayList<Student>();
list.add(new Student(1,"张三",5));
list.add(new Student(2,"李四",4));
list.add(new Student(3,"王五",3));
list.add(new Student(4,"小明",2));
list.add(new Student(5,"小黑",1));
ListSort<Student> listSort= new ListSort<Student>();
listSort.Sort(list, "getAge", "desc");
for(Student s:list){
System.out.println(s.getId()+s.getName()+s.getAge());
}
}
}
测试结果
1张三5
2李四4
3王五3
4小明2
5小黑1