猿问

java Comparator为何是函数式接口?

@FunctionalInterface
publicinterfaceComparator{
/**
*Comparesitstwoargumentsfororder.Returnsanegativeinteger,
*zero,orapositiveintegerasthefirstargumentislessthan,equal
*to,orgreaterthanthesecond.

*
*Intheforegoingdescription,thenotation
*sgn(expression)designatesthemathematical
*signumfunction,whichisdefinedtoreturnoneof-1,
*0,or1accordingtowhetherthevalueof
*expressionisnegative,zeroorpositive.

*
*Theimplementormustensurethatsgn(compare(x,y))==
*-sgn(compare(y,x))forallxandy.(This
*impliesthatcompare(x,y)mustthrowanexceptionifandonly
*ifcompare(y,x)throwsanexception.)

*
*Theimplementormustalsoensurethattherelationistransitive:
*((compare(x,y)>0)&&(compare(y,z)>0))implies
*compare(x,z)>0.

*
*Finally,theimplementormustensurethatcompare(x,y)==0
*impliesthatsgn(compare(x,z))==sgn(compare(y,z))forall
*z.

*
*Itisgenerallythecase,butnotstrictlyrequiredthat
*(compare(x,y)==0)==(x.equals(y)).Generallyspeaking,
*anycomparatorthatviolatesthisconditionshouldclearlyindicate
*thisfact.Therecommendedlanguageis"Note:thiscomparator
*imposesorderingsthatareinconsistentwithequals."
*
*@paramo1thefirstobjecttobecompared.
*@paramo2thesecondobjecttobecompared.
*@returnanegativeinteger,zero,orapositiveintegerasthe
*firstargumentislessthan,equalto,orgreaterthanthe
*second.
*@throwsNullPointerExceptionifanargumentisnullandthis
*comparatordoesnotpermitnullarguments
*@throwsClassCastExceptionifthearguments'typespreventthemfrom
*beingcomparedbythiscomparator.
*/
intcompare(To1,To2);
/**
*Indicateswhethersomeotherobjectis"equalto"this
*comparator.Thismethodmustobeythegeneralcontractof
*{@linkObject#equals(Object)}.Additionally,thismethodcanreturn
*trueonlyifthespecifiedobjectisalsoacomparator
*anditimposesthesameorderingasthiscomparator.Thus,
*comp1.equals(comp2)impliesthatsgn(comp1.compare(o1,
*o2))==sgn(comp2.compare(o1,o2))foreveryobjectreference
*o1ando2.

*
*Notethatitisalwayssafenottooverride
*Object.equals(Object).However,overridingthismethodmay,
*insomecases,improveperformancebyallowingprogramstodetermine
*thattwodistinctcomparatorsimposethesameorder.
*
*@paramobjthereferenceobjectwithwhichtocompare.
*@returntrueonlyifthespecifiedobjectisalso
*acomparatoranditimposesthesameorderingasthis
*comparator.
*@seeObject#equals(Object)
*@seeObject#hashCode()
*/
booleanequals(Objectobj);
接口中明明有两个抽象方法,intcompare(To1,To2);和booleanequals(Objectobj);为何还是函数式接口???
素胚勾勒不出你
浏览 1234回答 2
2回答

繁花如伊

Thismethodmustobeythegeneralcontractof{@linkObject#equals(Object)}.

交互式爱情

public@interfaceFunctionalInterface官方文档:Ifaninterfacedeclaresanabstractmethodoverridingoneofthepublicmethodsofjava.lang.Object,thatalsodoesnotcounttowardtheinterface'sabstractmethodcountsinceanyimplementationoftheinterfacewillhaveanimplementationfromjava.lang.Objectorelsewhere.如果接口声明了一个覆盖java.lang.Object的全局方法之一的抽象方法,那么它不会计入接口的抽象方法数量中,因为接口的任何实现都将具有java.lang.Object或其他地方的实现。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答