首先,我的待排序的类TieziAndImageClass中有一字段为String time,是时间来的,其格式为 yyyy-MM-dd HH:mm:ss 。要对这个类的多个实例进行排序,我就是依据这反应时间的字符串来排序的,时间旧的排前,时间新的排后,为此自定义了一个类继承了Compretor
public class TimeCompreter implements Comparator
{
public int compare(Object object1,Object object2)
{
TieziAndImageClass tiezi1=(TieziAndImageClass)object1;
TieziAndImageClass tiezi2=(TieziAndImageClass)object2;
String time1=tiezi1.tiezi.getTime(); //获取反应时间的字符串
String time2=tiezi2.tiezi.getTime();
int yearResult=-2;
String year1=time1.substring(0, 3);
String year2=time2.substring(0, 3);
int intYear1=Integer.parseInt(year1);
int intYear2=Integer.parseInt(year2);
if(intYear1>intYear2) yearResult=1;
else if (intYear1==intYear2) yearResult=0;
else if(intYear1<intYear2) yearResult=-1;
if(yearResult==1 || yearResult==-1) return yearResult;
int monthResult=-2;
String month1=time1.substring(5,6);
String month2=time2.substring(5,6);
int intMonth1=Integer.parseInt(month1);
int intMonth2=Integer.parseInt(month2);
if(intMonth1>intMonth2) monthResult=1;
else if (intMonth1==intMonth2) monthResult=0;
else if(intMonth1<intMonth2) monthResult=-1;
if(monthResult==1 || monthResult==-1) return monthResult;
int dayResult=-2;
String day1=time1.substring(8,9);
String day2=time2.substring(8,9);
int intDay1=Integer.parseInt(day1);
int intDay2=Integer.parseInt(day2);
if(intDay1>intDay2) dayResult=1;
else if (intDay1==intDay2) dayResult=0;
else if(intDay1<intDay2) dayResult=-1;
if(dayResult==1 || dayResult==-1) return dayResult;
int hourResult=-2;
String hour1=time1.substring(11,12);
String hour2=time2.substring(11,12);
int intHour1=Integer.parseInt(hour1);
int intHour2=Integer.parseInt(hour2);
if(intHour1>intHour2) hourResult=1;
else if (intHour1==intHour2) hourResult=0;
else if(intHour1<intHour2) hourResult=-1;
if(hourResult==1 || hourResult==-1) return hourResult;
int minuteResult=-2;
String minute1=time1.substring(14,15);
String minute2=time2.substring(14,15);
int intMinute1=Integer.parseInt(minute1);
int intMinute2=Integer.parseInt(minute2);
if(intMinute1>intMinute2) minuteResult=1;
else if (intMinute1==intMinute2) minuteResult=0;
else if(intMinute1<intMinute2) minuteResult=-1;
if(minuteResult==1 || minuteResult==-1) return minuteResult;
int secondResult=-2;
String second1=time1.substring(17,18);
String second2=time2.substring(17,18);
int intSecond1=Integer.parseInt(second1);
int intSecond2=Integer.parseInt(second2);
if(intSecond1>intSecond2) secondResult=1;
else if (intSecond1==intSecond2) secondResult=0;
else if(intSecond1<intSecond2) secondResult=-1;
return secondResult;
}
}
按如下方式来使用
Collectios.sort(list对象,new TimeCompretor());
但是最后排序结果很乱,没能按预期的旧的排前,新的排后这样来排,实际中的是旧的有点排前也有点排到后面去了,总之排完之后的顺序混乱,求指点一下