62,612
社区成员
发帖
与我相关
我的任务
分享
public class OrderBy<T> implements Comparator<T>{
private String fieldName ="";
public String getArgs() {
return fieldName;
}
public void setArgs(String args) {
this.fieldName = args;
}
public OrderBy(String str){
fieldName = str;
}
public OrderBy(){
System.out.println("OrderBy done...");
}
public int compare(T o1, T o2) {
// TODO Auto-generated method stub
System.out.println("compare done...");
Object obj1 = this.invokeMethod(o1, fieldName, new Object[0]);
Object obj2 = this.invokeMethod(o2, fieldName, new Object[0]);
System.out.println(obj1.toString() + " " + obj2.toString());
if(obj1 == null || obj2 == null){
return 0;
}else{
return obj1.toString().compareTo(obj2.toString());
}
}
@SuppressWarnings("unchecked")
private Object invokeMethod(T obj,String methodName, Object[] args){
Object object = null;
@SuppressWarnings("rawtypes")
Class ownerClass = obj.getClass();
@SuppressWarnings("rawtypes")
Class[] argsClass = new Class[args.length];
for(int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Method method;
try {
methodName = "get" + methodName;
method = ownerClass.getMethod(methodName, argsClass);
object = method.invoke(obj, args);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
}
return object;
}
}
int i;
int j;
int t;
//角色对应权限数数量
int[] a={47,22,6,17,33};
//用户角色ID
int[] b={1,2,3,4,5};
for(i=0;i<a.length-1;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
t=b[i];
b[i]=b[j];
b[j]=t;
}
}
}
for(i=0;i<a.length;i++)
{
System.out.println(a[i]+" "+b[i]);
}
public class MapSorttingDemo {
public static void main(String[] args) {
List roles = new ArrayList();
roles.add(new Role(1, 47));
roles.add(new Role(2, 22));
roles.add(new Role(3, 6));
roles.add(new Role(4, 17));
roles.add(new Role(5, 33));
Collections.sort(roles); //排序
for ( Object r : roles)
System.out.println(((Role)r).getId());
}
}
class Role implements Comparable{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
private int weight;
public Role (int id, int weight){
this.id = id;
this.weight = weight;
}
@Override
public int compareTo(Object o) { //根据权重排序
return Integer.signum(((Role)o).weight - weight);
}
}
用户角色ID 角色对应权限数数量
1 47
2 22
3 6
4 17
5 33
. .
. .
. .
. .