-
- 参数类型
-
T- 可以将此对象与之进行比较的对象的类型
- All Known Subinterfaces:
-
AnnotationTypeDoc,AnnotationTypeElementDoc,ArrayType,ByteValue,CharValue,ChronoLocalDate,ChronoLocalDateTime<D>,Chronology,ChronoZonedDateTime<D>,ClassDoc,ClassType,ConstructorDoc,Delayed,Doc,DoubleValue,ExecutableMemberDoc,Field,FieldDoc,FloatValue,IntegerValue,InterfaceType,LocalVariable,Location,LongValue,MemberDoc,方法,MethodDoc,Name,PackageDoc,Path,ProcessHandle,ProgramElementDoc,ReferenceType,RootDoc,RunnableScheduledFuture<V>,ScheduledFuture<V>,SerialFieldTag,ShortValue
- 所有已知实现类:
-
AbstractChronology,AbstractRegionPainter.PaintContext.CacheMode,AccessibleAction,AccessibleAttribute,AccessibleRole,AccessMode,AclEntryFlag,AclEntryPermission,AclEntryType,AddressingFeature.Responses,Alert.AlertType,Animation.Status,ArcType,AssociationChangeNotification.AssocChangeEvent,AttributeTree.ValueKind,Authenticator.RequestorType,BackgroundRepeat,BigDecimal,BigInteger,BlendMode,BlurType,Boolean,BorderRepeat,ButtonBar.ButtonData,Byte,ByteBuffer,CacheHint,Calendar,CardTerminals.State,CatalogFeatures.Feature,CertPathValidatorException.BasicReason,Character,Character.UnicodeScript,CharBuffer,Charset,ChronoField,ChronoUnit,ClientInfoStatus,Collation,CollationKey,Collector.Characteristics,Component.BaselineResizeBehavior,CompositeName,CompoundName,ConditionalFeature,ContentDisplay,ConversionComparator.Comparison,CRLReason,CryptoPrimitive,CullFace,CycleMethod,Date,Date,DayOfWeek,DepthTest,Desktop.ActionDesktop.Action,Diagnostic.Kind,Diagnostic.Kind,Dialog.ModalExclusionType,Dialog.ModalityType,Doclet.Option.Kind,DocletEnvironment.ModuleMode,DocTree.Kind,DocumentationTool.Location,Double,DoubleBuffer,DrawMode,DrbgParameters.Capability,DropMode,Duration,Duration,ElementKind,Elements.Origin,ElementType,Enum,File,FileTime,FileVisitOption,FileVisitResult,FillRule,Float,FloatBuffer,FocusEvent.Cause,FontPosture,FontSmoothingType,FontWeight,FormatStyle,Formatter.BigDecimalLayoutForm,FormSubmitEvent.MethodType,GraphicsDevice.WindowTranslucency,GregorianCalendar,GroupLayout.Alignment,HandlerResult,HijrahChronology,HijrahDate,HijrahEra,HorizontalDirection,HPos,HTMLEditorSkin.Command,HttpClient.Redirect,HttpClient.Version,InputMethodHighlight,InquireType,Instant,IntBuffer,Integer,IsoChronology,IsoEra,JapaneseChronology,JapaneseDate,JavaFileObject.Kind,JConsoleContext.ConnectionStateJConsoleContext.ConnectionState,JDBCType,JTable.PrintMode,KeyCode,KeyCombination.ModifierValue,KeyRep.Type,LambdaExpressionTree.BodyKind,LanguageVersion,LayoutStyle.ComponentPlacement,LdapName,LineChart.SortingPolicy,LinkOption,LocalDate,LocalDateTime,Locale.Category,Locale.FilteringMode,Locale.IsoCountryCode,LocalTime,Long,LongBuffer,MappedByteBuffer,Match,MatrixType,MediaException.Type,MediaPlayer.Status,MemberReferenceTree.ReferenceMode,MemoryType,MessageContext.Scope,MinguoChronology,MinguoDate,MinguoEra,Modality,Modifier,ModuleDescriptor,ModuleDescriptor.Exports,ModuleDescriptor.Exports.Modifier,ModuleDescriptor.Modifier,ModuleDescriptor.Opens,ModuleDescriptor.Opens.Modifier,ModuleDescriptor.Provides,ModuleDescriptor.Requires,ModuleDescriptor.Requires.Modifier,ModuleDescriptor.Version,ModuleElement.DirectiveKind,ModuleTree.ModuleKind,Month,MonthDay,MouseButton,MultipleGradientPaint.ColorSpaceType,MultipleGradientPaint.CycleMethod,NestingKind,NodeOrientation,Normalizer.Form,NumericShaper.Range,ObjectInputFilter.Status,ObjectNameObjectName,ObjectStreamField,OffsetDateTime,OffsetTime,Orientation,OverrunStyle,PageOrientation,PathTransition.OrientationType,PeerAddressChangeNotification.AddressChangeEvent,PixelFormat.Type,PKIXReason,PKIXRevocationChecker.Option,PopupWindow.AnchorLocation,Pos,PosixFilePermission,Preloader.StateChangeNotification.Type,PrintColor,Printer.MarginType,PrinterJob.JobStatus,PrintQuality,PrintSides,Priority,ProcessBuilder.Redirect.Type,Proxy.Type,PseudoColumnUsage,QuitStrategy,Rdn,ResolverStyle,Resource.AuthenticationType,RetentionPolicy,RoundingMode,RowFilter.ComparisonType,RowIdLifetime,RowSorterEvent.Type,Runtime.Version,ScrollEvent.HorizontalTextScrollUnits,ScrollEvent.VerticalTextScrollUnits,ScrollPane.ScrollBarPolicy,SelectionMode,Service.Mode,Short,ShortBuffer,Side,SignStyle,SizeUnits,Snippet.Kind,Snippet.Status,Snippet.SubKind,SOAPBinding.ParameterStyle,SOAPBinding.Style,SOAPBinding.Use,SocketFlow.Status,SortOrder,SourceCodeAnalysis.Completeness,SourceVersion,SSLEngineResult.HandshakeStatus,SSLEngineResult.StatusSSLEngineResult.Status,StackWalker.Option,StageStyle,StandardCopyOption,StandardLocation,StandardNamespace,StandardOpenOption,StandardOperation,StandardProtocolFamily,String,StrokeLineCap,StrokeLineJoin,StrokeType,StyleOrigin,SwingWorker.StateValue,System.Logger.Level,TableColumn.SortType,TabPane.TabClosingPolicy,Taglet.Location,Taskbar.Feature,Taskbar.State,TaskEvent.Kind,TextAlignment,TextBoundsType,TextInputControlSkin.Direction,TextInputControlSkin.TextUnit,TextStyle,ThaiBuddhistChronology,ThaiBuddhistDate,ThaiBuddhistEra,Thread.State,Time,Timestamp,TimeUnit,TouchPoint.State,TransferMode,TrayIcon.MessageType,Tree.Kind,Tree.Kind,TreeSortMode,TreeTableColumn.SortType,TypeKind,URI,UserSessionEvent.Reason,UUID,VarHandle.AccessMode,VerticalDirection,VMOption.Origin,VPos,WebParam.Mode,WebSocket.MessagePart,Window.Type,Worker.State,XmlAccessOrder,XmlAccessType,XmlNsFormXmlNsForm,XPathEvaluationResult.XPathResultType,Year,YearMonth,ZonedDateTime,ZoneOffset,ZoneOffsetTransition,ZoneOffsetTransitionRule.TimeDefinition
public interface Comparable<T>该接口对实现它的每个类的对象强加一个整体排序。 这个排序被称为类的自然排序 ,类的compareTo方法被称为其自然比较方法 。实现此接口的对象的列表(和数组)可以自动排序
Collections.sort(和Arrays.sort)。 实现该接口的对象,可以使用如在键sorted map或作为在元件sorted set ,而不需要指定一个comparator 。一类的自然排序
C被说成是与equals一致 ,当且仅当e1.compareTo(e2) == 0具有相同的布尔值e1.equals(e2),每e1和e2类C。 注意,null不是任何类的实例,而e.compareTo(null)应该抛出一个NullPointerException即使e.equals(null)返回false。强烈建议(尽管不需要)自然排序与等于一致。 这是因为,当没有显式比较器的排序集(和排序映射)与其自然排序与equals不一致的元素(或键)一起使用时会“奇怪地”。 特别地,这种排序集合(或排序映射)违反了用于设定(或映射)的通用合同,其按照
equals方法定义。例如,如果加上两个键
a和b使得(!a.equals(b) && a.compareTo(b) == 0)到有序集合不使用显式的比较器,所述第二add(有序集合不增加的大小和)操作返回false因为a和b是等价从排序集的角度。实际上,实现
Comparable所有Java核心类都具有与等于一致的自然排序。 一个例外是java.math.BigDecimal,其自然排序等于BigDecimal具有相等值和不同精度(例如4.0和4.00)的对象。对于数学倾斜,定义给定类C的自然排序的关系是:
这个总订单的商是:{(x, y) such that x.compareTo(y) <= 0}.它从合同紧跟{(x, y) such that x.compareTo(y) == 0}.compareTo,该商数是一个等价关系C,那自然排序是一个总的顺序C。 当我们说一个类的自然排序与equals一致时 ,我们意味着自然排序的商是由类的equals(Object)方法定义的等价关系:{(x, y) such that x.equals(y)}.此接口是Java Collections Framework的成员。
- 从以下版本开始:
- 1.2
- 另请参见:
-
Comparator
-
-
方法详细信息
-
compareTo
int compareTo(T o)
将此对象与指定的对象进行比较以进行排序。 返回一个负整数,零或正整数,因为该对象小于,等于或大于指定对象。实现程序必须确保
sgn(x.compareTo(y)) == -sgn(y.compareTo(x))所有x和y。 (这意味着x.compareTo(y)必须抛出异常iffy.compareTo(x)引发异常。)实施者还必须确保关系是可传递的:
(x.compareTo(y) > 0 && y.compareTo(z) > 0)意味着x.compareTo(z) > 0。最后,实施者必须确保
x.compareTo(y)==0意味着sgn(x.compareTo(z)) == sgn(y.compareTo(z)),全部为z。强烈建议,但不要严格要求
(x.compareTo(y)==0) == (x.equals(y))。 一般来说,任何实现Comparable接口并违反这种情况的类都应该清楚地表明这一点。 推荐的语言是“注意:此类具有与equals不一致的自然排序”。在前面的描述中,符号
sgn(表达)表示数学符号函数,其被定义为返回之一-1,0,或1分别根据表达式的值是否为负,零或正。- 参数
-
o- 要比较的对象。 - 结果
- 负整数,零或正整数,因为该对象小于,等于或大于指定对象。
- 异常
-
NullPointerException- 如果指定的对象为空 -
ClassCastException- 如果指定的对象的类型阻止它与该对象进行比较。
-
-