The Comparable<t> interface in Java

Source: Internet
Author: User

When using a normal array, you can call Java.util.Arrays.sort () if you want to sort the data. However, to sort the arrays by this way, the objects in the array are also required to implement the Comparable<t> interface.

 Packageorg.lyk.entities; Public classBookImplementsComparable<book>{    Static intTotalCount; PrivateString title; @Override PublicString toString () {return"Book [title=" + title + ", price=" + Price + "]"; }    Private floatPrice ;  PublicBook () {} PublicBook (String title,floatPrice ) {        Super();  This. title =title;  This. Price =Price ; } @Override Public intcompareTo (Book O) {//private String title;//private float price;//private String category;//private Author Author;                if( This. Price <O.price)return-1; Else if( This. Price >O.price)return1; if( This. Title.compareto (o.title)! = 0)            return  This. Title.compareto (O.title); return0; } }

 PackageOrg.lyk.main;ImportOrg.lyk.entities.Book; Public classmain{ Public Static voidMain (string[] args) {book[] books=Newbook[] {NewBook ("Java", 85),                        NewBook ("Oracle", 99),                        NewBook ("HTML5", 85),                        NewBook ("JSP", 64),                        NewBook ("Servlet", 99)                };        Java.util.Arrays.sort (books);  for(book item:books) {System.out.println (item); } System.out.println ((""instanceofString)); }}

The Comparable<t> interface in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.