模块 java.base
 java.lang

接口 Comparable<T>

类型参数:
T - 该对象可能与之比较的对象类型
所有已知的子接口:
ArrayType , ByteValue , CharValue , ChronoLocalDate , ChronoLocalDateTime<D> , Chronology , ChronoZonedDateTime<D> , ClassType , Delayed , DoubleValue , Field , FloatValue , IntegerValue , InterfaceType , LocalVariable , Location , LongValue , Method , Name , Path , ProcessHandle , ReferenceType , RunnableScheduledFuture<V> , ScheduledFuture<V> , ShortValue
所有已知的实现类:
AbstractChronology , AbstractRegionPainter.PaintContext.CacheMode , AccessFlag , AccessFlag.Location , AccessMode , AclEntryFlag , AclEntryPermission , AclEntryType , AssociationChangeNotification.AssocChangeEvent , AttributeTree.ValueKind , Authenticator.RequestorType , BigDecimal , BigInteger , Boolean , Byte , ByteBuffer , Calendar , CardTerminals.State , CaseTree.CaseKind , CatalogFeatures.Feature , CertPathValidatorException.BasicReason , Character , Character.UnicodeScript , CharBuffer , Charset , ChronoField , ChronoUnit , ClassFileFormatVersion , ClientInfoStatus , CollationKey , Collector.Characteristics , Component.BaselineResizeBehavior , CompositeName , CompoundName , ConversionComparator.Comparison , CRLReason , CryptoPrimitive , Date , Date , DayOfWeek , Desktop.Action , Diagnostic.Kind , Dialog.ModalExclusionType , Dialog.ModalityType , DirectMethodHandleDesc.Kind , Doclet.Option.Kind , DocletEnvironment.ModuleMode , DocTree.Kind , DocumentationTool.Location , Double , DoubleBuffer , DrbgParameters.Capability , DropMode , Duration , ElementKind , Elements.Origin , ElementType , EnhancedForLoopTree.DeclarationKindPREVIEW , Enum , File , FileTime , FileVisitOption , FileVisitResult , Float , FloatBuffer , FocusEvent.Cause , FormatStyle , Formatter.BigDecimalLayoutForm , FormSubmitEvent.MethodType , Future.State , GraphicsDevice.WindowTranslucency , GregorianCalendar , GroupLayout.Alignment , HandlerResult , HijrahChronology , HijrahDate , HijrahEra , HotSpotDiagnosticMXBean.ThreadDumpFormatPREVIEW , HttpClient.Redirect , HttpClient.Version , InquireType , InstanceOfTree.TestKindPREVIEW , Instant , IntBuffer , Integer , IsoChronology , IsoEra , JapaneseChronology , JapaneseDate , JavaFileObject.Kind , JConsoleContext.ConnectionState , JDBCType , JTable.PrintMode , KeyRep.Type , LambdaExpressionTree.BodyKind , LayoutStyle.ComponentPlacement , LdapName , LinkOption , LocalDate , LocalDateTime , Locale.Category , Locale.FilteringMode , Locale.IsoCountryCode , LocalTime , Long , LongBuffer , MappedByteBuffer , MemberReferenceTree.ReferenceMode , MemoryType , MethodHandles.Lookup.ClassOption , MinguoChronology , MinguoDate , MinguoEra , 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 , MultipleGradientPaint.ColorSpaceType , MultipleGradientPaint.CycleMethod , NestingKind , Normalizer.Form , NumberFormat.Style , NumericShaper.Range , ObjectInputFilter.Status , ObjectName , ObjectStreamField , OffsetDateTime , OffsetTime , PeerAddressChangeNotification.AddressChangeEvent , PKIXReason , PKIXRevocationChecker.Option , PosixFilePermission , ProcessBuilder.Redirect.Type , Proxy.Type , PseudoColumnUsage , QuitStrategy , Rdn , RecordingState , ResolverStyle , RetentionPolicy , RoundingMode , RowFilter.ComparisonType , RowIdLifetime , RowSorterEvent.Type , Runtime.Version , Short , ShortBuffer , SignStyle , SimpleFileServer.OutputLevel , Snippet.Kind , Snippet.Status , Snippet.SubKind , SortOrder , SourceCodeAnalysis.Attribute , SourceCodeAnalysis.Completeness , SourceVersion , SSLEngineResult.HandshakeStatus , SSLEngineResult.Status , StackWalker.Option , StandardCopyOption , StandardLocation , StandardNamespace , StandardOpenOption , StandardOperation , StandardProtocolFamily , String , StringBuffer , StringBuilder , SwingWorker.StateValue , System.Logger.Level , Taglet.Location , Taskbar.Feature , Taskbar.State , TaskEvent.Kind , TextStyle , ThaiBuddhistChronology , ThaiBuddhistDate , ThaiBuddhistEra , Thread.State , Time , Timestamp , TimeUnit , TrayIcon.MessageType , Tree.Kind , TypeKind , URI , UserSessionEvent.Reason , UUID , VarHandle.AccessMode , VectorShape , VMOption.Origin , Window.Type , XPathEvaluationResult.XPathResultType , Year , YearMonth , ZonedDateTime , ZoneOffset , ZoneOffsetTransition , ZoneOffsetTransitionRule.TimeDefinition

public interface Comparable<T>
这个接口对实现它的每个类的对象强加了一个总的顺序。这个顺序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较法.

实现此接口的对象列表(和数组)可以按 Collections.sort (和 Arrays.sort )自动排序。实现此接口的对象可以用作 分类map 中的键或 排序集 中的元素,而无需指定 comparator

C 的自然顺序据说是一致当且仅当 e1.compareTo(e2) == 0 对于类 C 的每个 e1e2 具有与 e1.equals(e2) 相同的boolean。请注意,null 不是任何类的实例,并且 e.compareTo(null) 应该抛出 NullPointerException,即使 e.equals(null) 返回 false

强烈建议(虽然不是必需的)自然排序与 equals 一致。之所以如此,是因为没有显式比较器的排序集(和排序映射)在与自然排序与 equals 不一致的元素(或键)一起使用时表现得“奇怪”。特别是,这样的有序集合(或有序映射)违反了集合(或映射)的一般契约,它是根据 equals 方法定义的。

例如,如果添加两个键 ab 使得 (!a.equals(b) && a.compareTo(b) == 0) 到不使用显式比较器的有序集合,则第二个 add 操作返回 false(并且有序集合的大小不增加)因为 ab 是等价的从排序集的角度来看。

实际上,所有实现Comparable 的 Java 核心类都具有与 equals 一致的自然顺序。一个例外是 BigDecimal ,它的 自然排序 等同于具有相同数值和不同表示(例如 4.0 和 4.00)的 BigDecimal 对象。 BigDecimal.equals() 返回 true,两个 BigDecimal 对象的表示和数值必须相同。

对于喜欢数学的人来说,关系定义给定类 C 的自然顺序是:


    {(x, y) such that x.compareTo(y) <= 0}.
  
对于这个总订单是:

    {(x, y) such that x.compareTo(y) == 0}.
  
它立即从 compareTo 的合同得出商是等价关系C 上,自然顺序是总订单C 上。当我们说一个类的自然顺序是一致,我们的意思是自然排序的商是由类的equals(Object) 方法定义的等价关系:
   {(x, y) such that x.equals(y)}. 

也就是说,当一个类的自然排序与equals一致时,equals方法的等价关系定义的等价类和compareTo方法的商定义的等价类是相同的。

此接口是 Java 集合框架 的成员。

自从:
1.2
参见:
  • 方法总结

    修饰符和类型
    方法
    描述
    int
    比较此对象与指定对象的顺序。
  • 方法详情

    • compareTo

      int compareTo(T  o)
      比较此对象与指定对象的顺序。当此对象小于、等于或大于指定对象时,返回负整数、零或正整数。

      实施者必须确保所有 xysignum (x.compareTo(y)) == -signum(y.compareTo(x))。 (这意味着当且仅当 y.compareTo(x) 抛出异常时 x.compareTo(y) 必须抛出异常。)

      实现者还必须确保关系是可传递的:(x.compareTo(y) > 0 && y.compareTo(z) > 0) 表示 x.compareTo(z) > 0

      最后,实施者必须确保 x.compareTo(y)==0 暗示 signum(x.compareTo(z)) == signum(y.compareTo(z)) ,对于所有 z

      API 注意:
      强烈推荐,但是not严格要求 (x.compareTo(y)==0) == (x.equals(y)) 。一般来说,任何实现 Comparable 接口并违反此条件的类都应清楚地表明这一事实。推荐的语言是“注意:此类具有与 equals 不一致的自然顺序”。
      参数:
      o - 要比较的对象。
      返回:
      负整数、零或正整数,因为此对象小于、等于或大于指定对象。
      抛出:
      NullPointerException - 如果指定对象为空
      ClassCastException - 如果指定对象的类型阻止它与该对象进行比较。