Comparable接口

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);对两个不同的对象进行比较。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值