- 型パラメータ:
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,AttributeMapper.AttributeStabilityPREVIEW,AttributeTree.ValueKind,Authenticator.RequestorType,BigDecimal,BigInteger,Boolean,Byte,ByteBuffer,Calendar,CardTerminals.State,CaseTree.CaseKind,CatalogFeatures.Feature,CatalogResolver.NotFoundAction,CertPathValidatorException.BasicReason,Character,Character.UnicodeScript,CharBuffer,Charset,ChronoField,ChronoUnit,ClassFile.AttributesProcessingOptionPREVIEW,ClassFile.ConstantPoolSharingOptionPREVIEW,ClassFile.DeadCodeOptionPREVIEW,ClassFile.DeadLabelsOptionPREVIEW,ClassFile.DebugElementsOptionPREVIEW,ClassFile.LineNumbersOptionPREVIEW,ClassFile.ShortJumpsOptionPREVIEW,ClassFile.StackMapsOptionPREVIEW,ClassFileFormatVersion,ClassPrinter.VerbosityPREVIEW,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,ListFormat.Style,ListFormat.Type,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,OpcodePREVIEW,Opcode.KindPREVIEW,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,Signature.TypeArg.WildcardIndicatorPREVIEW,SignStyle,SimpleFileServer.OutputLevel,Snippet.Kind,Snippet.Status,Snippet.SubKind,SortOrder,SourceCodeAnalysis.Attribute,SourceCodeAnalysis.Completeness,SourceVersion,SSLEngineResult.HandshakeStatus,SSLEngineResult.Status,StackMapFrameInfo.SimpleVerificationTypeInfoPREVIEW,StackWalker.Option,StandardCopyOption,StandardLocation,StandardNamespace,StandardOpenOption,StandardOperation,StandardProtocolFamily,String,StringBuffer,StringBuilder,StructuredTaskScope.Subtask.StatePREVIEW,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,TypeAnnotation.TargetTypePREVIEW,TypeAnnotation.TypePathComponent.KindPREVIEW,TypeKindPREVIEW,TypeKind,URI,UserSessionEvent.Reason,UUID,VarHandle.AccessMode,VectorShape,VMOption.Origin,Window.Type,XPathEvaluationResult.XPathResultType,Year,YearMonth,ZonedDateTime,ZoneOffset,ZoneOffsetTransition,ZoneOffsetTransitionRule.TimeDefinition
compareToメソッドは「自然比較メソッド」と呼ばれます。
このインタフェースを実装するオブジェクトのリスト(および配列)は、Collections.sort (およびArrays.sort)によって自動的にソートできます。 このインタフェースを実装するオブジェクトはソート・マップのキーとして使用したり、ソート・セットの要素として使用したりできますが、その際に、コンパレータを指定する必要はありません。
クラスCの自然順序付けは、e1.compareTo(e2) == 0がクラスCのe1およびe2ごとにe1.equals(e2)と同じブール値を持つ場合にのみ、「等しいと一貫性」と呼ばれます。 nullはどのクラスのインスタンスでもないため、e.equals(null)がfalseを返す場合でも、e.compareTo(null)はNullPointerExceptionをスローする必要があります。
自然順序付けでは、equalsと一貫性があることは、必須ではありませんが強く推奨されます。 これは、明示的なコンパレータを指定しないソート・セットやソート・マップを、自然順序付けがequalsと一貫性のない要素またはキーと一緒に使用すると、セットとマップの動作が保証されなくなるからです。 特に、このようなソートされたセット(またはマップのソート)は、equalsメソッドの観点から定義された、セット(またはマップ)の一般契約に違反します。
たとえば、明示的な比較子を使用しないソート済セットに(!a.equals(b) && a.compareTo(b) == 0)となるように2つのキーaおよびbを追加した場合、2番目のadd操作は、aおよびbはソート済セットのパースペクティブから同等であるため、false (ソートされたセットのサイズは増加しません)を返します。
Comparableを実装するすべてのJavaコア・クラスには、等しいと一貫性のある自然順序があります。 1つの例外はBigDecimalです。「自然順序付け」は、同じ数値および異なる表現(4.0や4.0 0など)を持つ BigDecimalオブジェクトを表します。 BigDecimal.equals()がtrueを返すには、2つの 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メソッドの等価関係で定義された等価クラスと、compareToメソッドのquotientで定義された等価クラスは同じです。
このインタフェースは、Java Collections Frameworkのメンバーです。
- 導入されたバージョン:
- 1.2
- 関連項目:
-
メソッドのサマリー
-
メソッドの詳細
-
compareTo
int compareTo(T o) このオブジェクトと指定されたオブジェクトの順序を比較します。 このオブジェクトが指定されたオブジェクトより小さい場合は負の整数、等しい場合はゼロ、大きい場合は正の整数を返します。実装者は、すべての
xおよびyに対してsignum(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を意味します。最後に、実装者は、すべての
zに対してx.compareTo(y)==0がsignum(x.compareTo(z)) == signum(y.compareTo(z))を示していることを確認する必要があります。- APIのノート:
(x.compareTo(y)==0) == (x.equals(y))を強くお勧めしますが、厳密には必要ありません。 一般的に、Comparableインタフェースを実装し、この条件に違反するクラスは、この事実を明確に表す必要があります。 お勧めする文言は「ノート: このクラスはequalsと一貫性のない自然順序付けを持ちます」です。- パラメータ:
o-比較対象のオブジェクト。- 戻り値:
- このオブジェクトが指定されたオブジェクトより小さい場合は負の整数、等しい場合はゼロ、大きい場合は正の整数
- 例外:
NullPointerException- 指定されたオブジェクトがnullの場合ClassCastException- 指定されたオブジェクトの型が原因で、このオブジェクトと比較できない場合
-