Interface Comparable. Type Parameters: T - the type of objects that this object may be compared to.
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Java™ PlatformStandard Ed. 7
PrevClass
NextClass
Frames
NoFrames
AllClasses
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
TypeParameters:T-thetypeofobjectsthatthisobjectmaybecomparedto
AllKnownSubinterfaces:
Delayed,Name,Path,RunnableScheduledFuture,ScheduledFuture
AllKnownImplementingClasses:
AbstractRegionPainter.PaintContext.CacheMode,AccessMode,AclEntryFlag,AclEntryPermission,AclEntryType,AddressingFeature.Responses,Authenticator.RequestorType,BigDecimal,BigInteger,Boolean,Byte,ByteBuffer,Calendar,CertPathValidatorException.BasicReason,Character,Character.UnicodeScript,CharBuffer,Charset,ClientInfoStatus,CollationKey,Component.BaselineResizeBehavior,CompositeName,CompoundName,CRLReason,CryptoPrimitive,Date,Date,Desktop.Action,Diagnostic.Kind,Dialog.ModalExclusionType,Dialog.ModalityType,Double,DoubleBuffer,DropMode,ElementKind,ElementType,Enum,File,FileTime,FileVisitOption,FileVisitResult,Float,FloatBuffer,Formatter.BigDecimalLayoutForm,FormSubmitEvent.MethodType,GraphicsDevice.WindowTranslucency,GregorianCalendar,GroupLayout.Alignment,IntBuffer,Integer,JavaFileObject.Kind,JTable.PrintMode,KeyRep.Type,LayoutStyle.ComponentPlacement,LdapName,LinkOption,Locale.Category,Long,LongBuffer,MappedByteBuffer,MemoryType,MessageContext.Scope,Modifier,MultipleGradientPaint.ColorSpaceType,MultipleGradientPaint.CycleMethod,NestingKind,Normalizer.Form,NumericShaper.Range,ObjectName,ObjectStreamField,PKIXReason,PosixFilePermission,ProcessBuilder.Redirect.Type,Proxy.Type,PseudoColumnUsage,Rdn,Resource.AuthenticationType,RetentionPolicy,RoundingMode,RowFilter.ComparisonType,RowIdLifetime,RowSorterEvent.Type,Service.Mode,Short,ShortBuffer,SOAPBinding.ParameterStyle,SOAPBinding.Style,SOAPBinding.Use,SortOrder,SourceVersion,SSLEngineResult.HandshakeStatus,SSLEngineResult.Status,StandardCopyOption,StandardLocation,StandardOpenOption,StandardProtocolFamily,String,SwingWorker.StateValue,Thread.State,Time,Timestamp,TimeUnit,TrayIcon.MessageType,TypeKind,URI,UUID,WebParam.Mode,Window.Type,XmlAccessOrder,XmlAccessType,XmlNsForm
publicinterfaceComparable
Thisinterfaceimposesatotalorderingontheobjectsofeachclassthat
implementsit.Thisorderingisreferredtoastheclass'snatural
ordering,andtheclass'scompareTomethodisreferredtoas
itsnaturalcomparisonmethod.
Lists(andarrays)ofobjectsthatimplementthisinterfacecanbesorted
automaticallybyCollections.sort(and
Arrays.sort).Objectsthatimplementthis
interfacecanbeusedaskeysinasortedmaporas
elementsinasortedset,withouttheneedto
specifyacomparator.
ThenaturalorderingforaclassCissaidtobeconsistent
withequalsifandonlyife1.compareTo(e2)==0has
thesamebooleanvaluease1.equals(e2)forevery
e1ande2ofclassC.Notethatnull
isnotaninstanceofanyclass,ande.compareTo(null)should
throwaNullPointerExceptioneventhoughe.equals(null)
returnsfalse.
Itisstronglyrecommended(thoughnotrequired)thatnaturalorderingsbe
consistentwithequals.Thisissobecausesortedsets(andsortedmaps)
withoutexplicitcomparatorsbehave"strangely"whentheyareusedwith
elements(orkeys)whosenaturalorderingisinconsistentwithequals.In
particular,suchasortedset(orsortedmap)violatesthegeneralcontract
forset(ormap),whichisdefinedintermsoftheequals
method.
Forexample,ifoneaddstwokeysaandbsuchthat
(!a.equals(b)&&a.compareTo(b)==0)toasorted
setthatdoesnotuseanexplicitcomparator,thesecondadd
operationreturnsfalse(andthesizeofthesortedsetdoesnotincrease)
becauseaandbareequivalentfromthesortedset's
perspective.
VirtuallyallJavacoreclassesthatimplementComparablehavenatural
orderingsthatareconsistentwithequals.Oneexceptionis
java.math.BigDecimal,whosenaturalorderingequates
BigDecimalobjectswithequalvaluesanddifferentprecisions
(suchas4.0and4.00).
Forthemathematicallyinclined,therelationthatdefines
thenaturalorderingonagivenclassCis:
{(x,y)suchthatx.compareTo(y)<=0}.
Thequotientforthistotalorderis:
{(x,y)suchthatx.compareTo(y)==0}.
ItfollowsimmediatelyfromthecontractforcompareTothatthe
quotientisanequivalencerelationonC,andthatthe
naturalorderingisatotalorderonC.Whenwesaythata
class'snaturalorderingisconsistentwithequals,wemeanthatthe
quotientforthenaturalorderingistheequivalencerelationdefinedby
theclass'sequals(Object)method:
{(x,y)suchthatx.equals(y)}.
Thisinterfaceisamemberofthe
JavaCollectionsFramework.
Since:
1.2
SeeAlso:Comparator
MethodSummary
Methods
ModifierandType
MethodandDescription
int
compareTo(T o)
Comparesthisobjectwiththespecifiedobjectfororder.
MethodDetail
compareTo
int compareTo(T o)
Comparesthisobjectwiththespecifiedobjectfororder.Returnsa
negativeinteger,zero,orapositiveintegerasthisobjectisless
than,equalto,orgreaterthanthespecifiedobject.
Theimplementormustensuresgn(x.compareTo(y))==
-sgn(y.compareTo(x))forallxandy.(This
impliesthatx.compareTo(y)mustthrowanexceptioniff
y.compareTo(x)throwsanexception.)
Theimplementormustalsoensurethattherelationistransitive:
(x.compareTo(y)>0&&y.compareTo(z)>0)implies
x.compareTo(z)>0.
Finally,theimplementormustensurethatx.compareTo(y)==0
impliesthatsgn(x.compareTo(z))==sgn(y.compareTo(z)),for
allz.
Itisstronglyrecommended,butnotstrictlyrequiredthat
(x.compareTo(y)==0)==(x.equals(y)).Generallyspeaking,any
classthatimplementstheComparableinterfaceandviolates
thisconditionshouldclearlyindicatethisfact.Therecommended
languageis"Note:thisclasshasanaturalorderingthatis
inconsistentwithequals."
Intheforegoingdescription,thenotation
sgn(expression)designatesthemathematical
signumfunction,whichisdefinedtoreturnoneof-1,
0,or1accordingtowhetherthevalueof
expressionisnegative,zeroorpositive.
Parameters:o-theobjecttobecompared.
Returns:anegativeinteger,zero,orapositiveintegerasthisobject
islessthan,equalto,orgreaterthanthespecifiedobject.
Throws:
NullPointerException-ifthespecifiedobjectisnull
ClassCastException-ifthespecifiedobject'stypepreventsit
frombeingcomparedtothisobject.
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Java™ PlatformStandard Ed. 7
PrevClass
NextClass
Frames
NoFrames
AllClasses
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
SubmitabugorfeatureForfurtherAPIreferenceanddeveloperdocumentation,seeJavaSEDocumentation.Thatdocumentationcontainsmoredetailed,developer-targeteddescriptions,withconceptualoverviews,definitionsofterms,workarounds,andworkingcodeexamples.Copyright©1993,2020,Oracleand/oritsaffiliates.Allrightsreserved.Useissubjecttolicenseterms.Alsoseethedocumentationredistributionpolicy.