Module java.base
Package java.lang

Interface 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, 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.ThreadDumpFormat, HttpClient.Redirect, HttpClient.Version, InquireType, 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, StructuredTaskScope.Subtask.State预览, 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)自动排序。实现此接口的对象可以用作排序映射中的键,或作为排序集合中的元素,而无需指定比较器

C的自然排序被称为与equals一致,当且仅当对于类C的每个e1e2e1.compareTo(e2) == 0具有与e1.equals(e2)相同的布尔值。请注意,null不是任何类的实例,即使e.equals(null)返回falsee.compareTo(null)也应该抛出NullPointerException

强烈建议(但不是必须的)自然排序与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一致时,我们的意思是自然排序的商是由类的equals(Object)方法定义的等价关系:
     {(x, y) such that x.equals(y)}. 

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

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

自 JDK 版本:
1.2
参见:
  • Method Summary

    Modifier and Type
    Method
    Description
    int
    compareTo(T o)
    将此对象与指定对象进行比较以确定顺序。
  • Method Details

    • 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 注意:
      强烈建议,但不是严格要求(x.compareTo(y)==0) == (x.equals(y))。一般来说,任何实现Comparable接口并违反此条件的类应清楚指出这一事实。推荐的语言是“注意:此类具有与equals不一致的自然排序。”
      参数:
      o - 要比较的对象。
      返回:
      一个负整数、零或正整数,表示此对象小于、等于或大于指定对象。
      抛出:
      NullPointerException - 如果指定对象为null
      ClassCastException - 如果指定对象的类型阻止其与此对象进行比较。