package org.apache.java.lib.test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class QueueTest {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student("zhangs", "2"));
studentList.add(new Student("lisi", "1"));
studentList.add(new Student("wangwu", "3"));
Student student = getMaxObject(studentList);
System.out.println(student.getName());
System.out.println(student.getNumber());
}
/**
* 返回容器中最大的元素(通过比较器)
*
* @param objList
* 容器
* @return 最大的元素
*
*/
public static <T> T getMaxObject(List<T> objList) {
if (objList == null || objList.size() == 0) {
return null;
}
return Collections.max(objList, new Comparator<T>() {
public int compare(T o1, T o2) {
int equalValue = 0;
try {
Field o1Field = o1.getClass().getDeclaredField("number");
o1Field.setAccessible(true);
Field o2Filed = o2.getClass().getDeclaredField("number");
o2Filed.setAccessible(true);
equalValue = Integer.parseInt(String.valueOf(o1Field.get(o1))) < Integer
.parseInt(String.valueOf(o2Filed.get(o2))) ? -1 : 1;
} catch (Exception e) {
System.out.println("你传输的数据有问题!");
e.printStackTrace();
return equalValue;
}
return equalValue;
}
});
}
}
转载于:https://my.oschina.net/u/1858909/blog/411073