[Java] 用 Comparator 实现排序
本文内容纲要:
最近正好用到Comparator
,发现能对不同类型的对象进行排序(当然排序依据还是基本类型),也不用自己实现排序算法,用起来很方便,所以简单记录一下。
本文地址:http://www.cnblogs.com/rossoneri/p/4549529.html
InterfaceComparator<T>
对任意类型集合对象进行整体排序,排序时将此接口的实现传递给Collections.sort方法或者Arrays.sort方法排序。
实现intcompare(To1,To2);
方法,返回正数,零,负数各代表大于,等于,小于。具体看代码。
简单例子:
publicclassTest{
privatefinalclassCompareNameimplementsComparator<Milan>{
booleanis_Ascend;
publicCompareName(booleanb){
//TODOAuto-generatedconstructorstub
is_Ascend=b;
}
@Override
publicintcompare(Milano1,Milano2){
//TODOAuto-generatedmethodstub
if(is_Ascend)
returno1.p_Name.compareTo(o2.p_Name);
else
returno2.p_Name.compareTo(o1.p_Name);
}
}
privatefinalclassCompareIdimplementsComparator<Milan>{
booleanis_Ascend;
publicCompareId(booleanb){
//TODOAuto-generatedconstructorstub
is_Ascend=b;
}
@Override
publicintcompare(Milano1,Milano2){
//TODOAuto-generatedmethodstub
inta,b;
if(is_Ascend){
a=o1.p_Id;
b=o2.p_Id;
}else{
a=o2.p_Id;
b=o1.p_Id;
}
if(a>b)
return1;
elseif(a==b)
return0;
else
return-1;
}
}
publicstaticvoidmain(String[]args){
Testt=newTest();
Milanp1=newMilan(1,"Dida");
Milanp2=newMilan(2,"Cafu");
Milanp3=newMilan(3,"Maldini");
MilanP4=newMilan(6,"Baresi");
Milanp5=newMilan(9,"Inzaghi");
MilanP6=newMilan(10,"Costa");
List<Milan>mList=newArrayList<Milan>();
mList.add(p1);
mList.add(P6);
mList.add(P4);
mList.add(p2);
mList.add(p5);
mList.add(p3);
System.out.println("初始顺序");
System.out.println("姓名 | 号码");
for(Milanp:mList){
System.out.println(p.p_Name+" | "+p.p_Id);
}
System.out.println();
System.out.println("对号码降序");
System.out.println("姓名 | 号码");
Collections.sort(mList,t.newCompareId(false));
for(Milanp:mList){
System.out.println(p.p_Name+" | "+p.p_Id);
}
System.out.println();
System.out.println("对姓名升序");
System.out.println("姓名 | 号码");
Collections.sort(mList,t.newCompareName(true));
for(Milanp:mList){
System.out.println(p.p_Name+" | "+p.p_Id);
}
}
}
输出结果:
初始顺序
姓名 | 号码
Dida | 1
Costa | 10
Baresi | 6
Cafu | 2
Inzaghi | 9
Maldini | 3对号码降序
姓名 | 号码
Costa | 10
Inzaghi | 9
Baresi | 6
Maldini | 3
Cafu | 2
Dida | 1对姓名升序
姓名 | 号码
Baresi | 6
Cafu | 2
Costa | 10
Dida | 1
Inzaghi | 9
Maldini | 3
sort方法第一个参数是一个list对象,排序结束后的结果就继续保存在这个list中,可以直接使用。
附上文档,不用再去查了
publicinterfaceComparator<T>
Acomparisonfunction,whichimposesatotalorderingonsomecollectionofobjects.Comparatorscanbepassedtoasortmethod(suchasCollections.sortorArrays.sort)toallowprecisecontroloverthesortorder.Comparatorscanalsobeusedtocontroltheorderofcertaindatastructures(suchassortedsetsorsortedmaps),ortoprovideanorderingforcollectionsofobjectsthatdon'thaveanaturalordering.
TheorderingimposedbyacomparatorconasetofelementsSissaidtobeconsistentwithequalsifandonlyifc.compare(e1,e2)==0hasthesamebooleanvaluease1.equals(e2)foreverye1ande2inS.
Cautionshouldbeexercisedwhenusingacomparatorcapableofimposinganorderinginconsistentwithequalstoorderasortedset(orsortedmap).Supposeasortedset(orsortedmap)withanexplicitcomparatorcisusedwithelements(orkeys)drawnfromasetS.IftheorderingimposedbyconSisinconsistentwithequals,thesortedset(orsortedmap)willbehave"strangely."Inparticularthesortedset(orsortedmap)willviolatethegeneralcontractforset(ormap),whichisdefinedintermsofequals.
Forexample,supposeoneaddstwoelementsaandbsuchthat(a.equals(b)&&c.compare(a,b)!=0)toanemptyTreeSetwithcomparatorc.Thesecondaddoperationwillreturntrue(andthesizeofthetreesetwillincrease)becauseaandbarenotequivalentfromthetreeset'sperspective,eventhoughthisiscontrarytothespecificationoftheSet.addmethod.
Note:Itisgenerallyagoodideaforcomparatorstoalsoimplementjava.io.Serializable,astheymaybeusedasorderingmethodsinserializabledatastructures(likeTreeSet,TreeMap).Inorderforthedatastructuretoserializesuccessfully,thecomparator(ifprovided)mustimplementSerializable.
Forthemathematicallyinclined,therelationthatdefinestheimposedorderingthatagivencomparatorcimposesonagivensetofobjectsSis:
{(x,y)suchthatc.compare(x,y)<=0}.
Thequotientforthistotalorderis:
{(x,y)suchthatc.compare(x,y)==0}.
ItfollowsimmediatelyfromthecontractforcomparethatthequotientisanequivalencerelationonS,andthattheimposedorderingisatotalorderonS.WhenwesaythattheorderingimposedbyconSisconsistentwithequals,wemeanthatthequotientfortheorderingistheequivalencerelationdefinedbytheobjects'equals(Object)method(s):
{(x,y)suchthatx.equals(y)}.
UnlikeComparable,acomparatormayoptionallypermitcomparisonofnullarguments,whilemaintainingtherequirementsforanequivalencerelation.
intcompare(To1,To2)
Comparesitstwoargumentsfororder.Returnsanegativeinteger,zero,orapositiveintegerasthefirstargumentislessthan,equalto,orgreaterthanthesecond.
Intheforegoingdescription,thenotationsgn(expression)designatesthemathematicalsignumfunction,whichisdefinedtoreturnoneof-1,0,or1accordingtowhetherthevalueofexpressionisnegative,zeroorpositive.
Theimplementormustensurethatsgn(compare(x,y))==-sgn(compare(y,x))forallxandy.(Thisimpliesthatcompare(x,y)mustthrowanexceptionifandonlyifcompare(y,x)throwsanexception.)
Theimplementormustalsoensurethattherelationistransitive:((compare(x,y)>0)&&(compare(y,z)>0))impliescompare(x,z)>0.
Finally,theimplementormustensurethatcompare(x,y)==0impliesthatsgn(compare(x,z))==sgn(compare(y,z))forallz.
Itisgenerallythecase,butnotstrictlyrequiredthat(compare(x,y)==0)==(x.equals(y)).Generallyspeaking,anycomparatorthatviolatesthisconditionshouldclearlyindicatethisfact.Therecommendedlanguageis"Note:thiscomparatorimposesorderingsthatareinconsistentwithequals."
Parameters:
o1-thefirstobjecttobecompared.
o2-thesecondobjecttobecompared.
Returns:
anegativeinteger,zero,orapositiveintegerasthefirstargumentislessthan,equalto,orgreaterthanthesecond.
booleanequals(Objectobj)
Indicateswhethersomeotherobjectis"equalto"thiscomparator.ThismethodmustobeythegeneralcontractofObject.equals(Object).Additionally,thismethodcanreturntrueonlyifthespecifiedobjectisalsoacomparatoranditimposesthesameorderingasthiscomparator.Thus,comp1.equals(comp2)impliesthatsgn(comp1.compare(o1,o2))==sgn(comp2.compare(o1,o2))foreveryobjectreferenceo1ando2.
NotethatitisalwayssafenottooverrideObject.equals(Object).However,overridingthismethodmay,insomecases,improveperformancebyallowingprogramstodeterminethattwodistinctcomparatorsimposethesameorder.
Overrides:
equalsinclassObject
Parameters:
obj-thereferenceobjectwithwhichtocompare.
Returns:
trueonlyifthespecifiedobjectisalsoacomparatoranditimposesthesameorderingasthiscomparator.
publicstatic<T>voidsort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparableusingthespecifiedcomparator(thatis,c.compare(e1,e2)mustnotthrowaClassCastExceptionforanyelementse1ande2inthelist).
Thissortisguaranteedtobestable:equalelementswillnotbereorderedasaresultofthesort.
Thesortingalgorithmisamodifiedmergesort(inwhichthemergeisomittedifthehighestelementinthelowsublistislessthanthelowestelementinthehighsublist).Thisalgorithmoffersguaranteednlog(n)performance.Thespecifiedlistmustbemodifiable,butneednotberesizable.Thisimplementationdumpsthespecifiedlistintoanarray,sortsthearray,anditeratesoverthelistresettingeachelementfromthecorrespondingpositioninthearray.Thisavoidsthen2log(n)performancethatwouldresultfromattemptingtosortalinkedlistinplace.
Parameters:
list-thelisttobesorted.
c-thecomparatortodeterminetheorderofthelist.Anullvalueindicatesthattheelements'naturalorderingshouldbeused.
本文内容总结:
原文链接:https://www.cnblogs.com/rossoneri/p/4549529.html