java 通用对象_java 通用对象排序

packageutil;importjava.lang.reflect.Field;importjava.util.Comparator;

@SuppressWarnings("rawtypes")public class ComparatorUtil implementsComparator{//要排序的属性名

privateString name;//是否升序

private boolean falg = true;/***@paramname 要排序的属性名,如果是基本类型的排序,请入null值

*@paramfalg false/true : 升序/降序*/

public ComparatorUtil(String name, booleanfalg) {super();this.name =name;this.falg =falg;

}

@Overridepublic intcompare(Object o1, Object o2) {int result = 0;//入参为空|参数类型不相等,都不进行处理。

if(o1 == null || o2 == null || !o1.getClass().getName().equals(o2.getClass().getName())){returnresult;

}//7大基本类型的处理(boolean除外.且把Collections.reverse()/Collections.sort()的事也做了)

if(isBaseType(o1)){//比较

returnbaseTypeOpt(o1,o2);

}try{

Field f1=o1.getClass().getDeclaredField(name);

Field f2=o2.getClass().getDeclaredField(name);//设置private可读

f1.setAccessible(true);

f2.setAccessible(true);

result=baseTypeOpt(f1.get(o1),f2.get(o2));

}catch (Exception e) { //异常懒得处理了,如果没有对应的属性,那就不排序了.(手动滑稽)

e.printStackTrace();

}returnresult;

}private intbaseTypeOpt(Object o1, Object o2) {int result = 0;if(o1 instanceofString){

result=o1.toString().compareTo(o2.toString());

}else if(o1 instanceofInteger){

result= ((Integer)o1) -((Integer)o2);

}else if(o1 instanceofDouble){if(((Double)o1 - (Double)o2) > 0){

result= 1;

}else if(((Double)o1 - (Double)o2) < 0){

result= -1;

}

}else if(o1 instanceofFloat){if(((Float)o1 - (Float)o2) > 0){

result= 1;

}else if(((Float)o1 - (Float)o2) < 0){

result= -1;

}

}else if(o1 instanceofCharacter){

result=((Character)o1).compareTo(((Character)o2));

}else if(o1 instanceofShort){

result= ((Short)o1) -((Short)o2);

}else if(o1 instanceofLong){if(((Long)o1 - (Long)o2) > 0){

result= 1;

}else if(((Long)o1 - (Long)o2) < 0){

result= -1;

}

}//降序

if(isFalg()){

result= -result;

}returnresult;

}private booleanisBaseType(Object o) {if((o instanceof String) || (o instanceofInteger)|| (o instanceof Double) || (o instanceofFloat)|| (o instanceof Character) || (o instanceofShort)|| (o instanceofLong)){return true;

}return false;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public booleanisFalg() {returnfalg;

}public void setFalg(booleanfalg) {this.falg =falg;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值