Comparable接口在lang包中,当某个类实现了此接口,则认为这个类的对象之间是可比较的。
所有已实现Comparable的类:
AbstractChronology , AbstractRegionPainter.PaintContext.CacheMode , AccessMode , AclEntryFlag , AclEntryPermission , AclEntryType , AddressingFeature.Responses , Authenticator.RequestorType , BigDecimal , BigInteger , Boolean , Byte , ByteBuffer , Calendar , CertPathValidatorException.BasicReason , Character , Character.UnicodeScript , CharBuffer , Charset , ChronoField , ChronoUnit , ClientInfoStatus , CollationKey , Collector.Characteristics , Component.BaselineResizeBehavior , CompositeName , CompoundName , CRLReason , CryptoPrimitive , Date , Date, DayOfWeek , Desktop.Action , Diagnostic.Kind , Dialog.ModalExclusionType , Dialog.ModalityType , DocumentationTool.Location , Double , DoubleBuffer, DropMode , Duration , ElementKind , ElementType , Enum , File , FileTime , FileVisitOption , FileVisitResult , Float , FloatBuffer , FormatStyle, Formatter.BigDecimalLayoutForm , FormSubmitEvent.MethodType , GraphicsDevice.WindowTranslucency , GregorianCalendar , GroupLayout.Alignment , HijrahChronology , HijrahDate , HijrahEra , Instant , IntBuffer , Integer , IsoChronology , IsoEra , JapaneseChronology , JapaneseDate , JavaFileObject.Kind , JDBCType , JTable.PrintMode , KeyRep.Type , LayoutStyle.ComponentPlacement , LdapName , LinkOption , LocalDate , LocalDateTime , Locale.Category , Locale.FilteringMode , LocalTime , Long , LongBuffer , MappedByteBuffer , MemoryType , MessageContext.Scope , MinguoChronology , MinguoDate , MinguoEra , Modifier , Month , MonthDay , MultipleGradientPaint.ColorSpaceType , MultipleGradientPaint.CycleMethod , NestingKind , Normalizer.Form , NumericShaper.Range , ObjectName , ObjectStreamField , OffsetDateTime , OffsetTime , PKIXReason , PKIXRevocationChecker.Option , PosixFilePermission , ProcessBuilder.Redirect.Type , Proxy.Type , PseudoColumnUsage , Rdn , ResolverStyle , Resource.AuthenticationType , RetentionPolicy , RoundingMode , RowFilter.ComparisonType , RowIdLifetime , RowSorterEvent.Type , Service.Mode , Short , ShortBuffer , SignStyle , SOAPBinding.ParameterStyle , 88405146987 697 , SOAPBinding.Use , SortOrder , SourceVersion , SSLEngineResult.HandshakeStatus , SSLEngineResult.Status , StandardCopyOption , StandardLocation , StandardOpenOption , StandardProtocolFamily , String , SwingWorker.StateValue , TextStyle , ThaiBuddhistChronology , ThaiBuddhistDate , ThaiBuddhistEra , Thread.State , Time , Timestamp , TimeUnit , TrayIcon.MessageType , TypeKind , URI , UUID , WebParam.Mode , Window.Type , XmlAccessOrder , XmlAccessType , XmlNsForm , Year , YearMonth , ZonedDateTime , ZoneOffset , ZoneOffsetTransition , ZoneOffsetTransitionRule.TimeDefinition
上面已经实现了Comparable接口的类,可以直接使用Arrays.sort自动对实现此接口的对象进行列表和数组排序。
Comparable的源码:
public interface Comparable<T> {
public int compareTo(T o);
//按照规定:如果 this 比 o 小,则返回一个负数,如果 this 比 o 大,则返回正数,否则返回0
}
当自己定义某个类实现此接口的时候,需要重写comparaTo方法,按照需求比较两个不同对象之间的比较。
public class Test {
public static void main(String[] args) {
Student[] students = { new Student("bob", 90.0) , new Student("jack", 89.0),new Student("mary", 99.0)};
Arrays.sort(students);
for(Student s:students)
System.out.println(s);
}
}
class Student implements Comparable<Student>
{
Student(String name,double score)
{
this.name = name;
this.score = score;
}
private double score;
private String name;
@Override
public int compareTo(Student o) {
return Double.compare(this.score, o.score); //借用Double包装类本身的compare方法
}
@Override
public String toString() {
return String.format("name:%s score:%f", name,score);
}
}
在自己定义类的实现Comparable接口之后,同时可以使用 Arrays.sort(students);对两个不同的对象进行比较。