Java generics application--t extends Comparable<? Super t>

Source: Internet
Author: User

In the observation of Java source code, the discovery of such a notation T extends comparable< Super t>. Can't help wondering why it's written like this? What are the benefits, extends and super's role here is a bit unclear.

Next, I'll share the code with you about my view of generics here.

  

1. <t extends comparable< what does super t>> mean ?

    • As you can see, this applies to generics in Java, so let's start by explaining the role of extends here.

extends followed by type, such as < any character extends class/interface > represents the upper-bound for generics. The sample code is as follows:

 import  java.util.*;  class  Demo<t extends  list>{}  public  class   test{ public  static  void   main (string[] args) {Demo  <ArrayList> p =  Null ; //  compiles correctly  //  here because ArrayList is a subclass of the list, through  //  }}  
    • After understanding the upper limit of the generics represented by extends, let's look at the role of Super, which, contrary to extends, represents the lower bound of the generic type.
    • So combined with the above two points, let's analyze what the whole meaning of this sentence means. First, extends limits the generic limit that T must be comparable< Super t> subclasses, then <? Super t> means that the lower limit of type in comparable<> is T!

 

2. <T extends Comparable<T>> <T extends Comparable<? super T>> What's the difference?

  The next step is to make a deeper impression of why you want to write code like this.

    • <T extends Comparable<T>>

It means that the type T must implement the Comparable interface, and that the type of the interface is T. In this way, instances of T can compare size to each other . Here we take the class GregorianCalendar in Java as an example.

The code looks like this:

 import   Java.util.GregorianCalendar;  class  Demo<t extends  comparable<t>>{}  //  Notice there's no? Super's  public  class   test{ public  static  void   main (string[] args) {Demo  <GregorianCalendar> p = null  ; }}

Compile the error here, because here the <t extends comparable<t>> equivalent <gregoriancalendar extends comparable< Gregoriancalendar>>, but the GregorianCalendar did not realize comparable<gregoriancalendar> Instead of just holding a comparable<calendar> inherited from the Calendar, this will cause an error in the absence of the limit .

    • <T extends Comparable<? super T>>  

  It means that the type T must implement the Comparable interface, and that the type of the interface is t or the any parent class of T. After this declaration, the instances of T and the instances of the parent class of T can compare size to each other . Also, take GregorianCalendar as an example. The code looks like this:

 import   Java.util.GregorianCalendar;  class  Demo<t extends  comparable<? super  T>>{}  public  class   test1{ public  static  void   main (string[] args) {Demo  <GregorianCalendar> p = null ; //  compiles correctly  }}  
at this point the compilation passes, this can be understood as <gregoriancalendar extends comparable<calendar>>! Because the Calendar is GregorianCalendar's parent class and GregorianCalendar implements Comparable<calendar>, it can be viewed in the API! 3. Example code demo  The code looks like this:
 Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;  Public classTest {//First statement: simple, low flexibility      Public Static<textendsComparable<t>>voidMySort1 (list<t>list)     {Collections.sort (list); }      //second type of statement: complex, high flexibility      Public Static<textendscomparable<?SuperT>>voidMySort2 (list<t>l) {collections.sort (list); }       Public Static voidMain (string[] args) {//Animal and dog two sequences are created in the main function, and then the sorting method is called to test them
The specific two version code in the main function will be shown below
} } classAnimalImplementsComparable<animal> { protected intAge ; PublicAnimal (intAge ) { This. Age =Age ; } //use age to compare size with another instance@Override Public intCompareTo (Animal other) {return This. Age-Other.age; } } classDogextendsAnimal { PublicDog (intAge ) { Super(age); } }

The above code consists of three classes:

    1. AnimalImplements an Comparable<Animal> interface to compare the size of instances by age
    2. Dog inherits from Animal and is its subclass.
    3. TestThe two sorting methods and methods for testing are provided in the class main() :
      • mySort1()Using <T extends Comparable<T>> type parameters
      • mySort2()Using <T extends Comparable<? super T>> type parameters
      • main()Test method. Here you will create a sequence of animal and dog two respectively, and then test it by calling the sort method.

  3.1 Test for MySort1 (), the main method code is as follows:

 //  Create a Animal List  list<animal > animals = new  arraylist<animal> (); Animals.add ( new  Animal (25 new  Dog (35 //  List<dog> dogs = new  arraylist<dog> () ;d Ogs.add ( new  Dog (5 Span style= "COLOR: #0000ff" >new  Dog (18 //  test MySort1 () method  mysort1 (animals); MySort1 (dogs);  

 Result compilation error, error message is:

 for the arguments (list<dog>)

The type parameter of the MySort1 () method is <t extends Comparable<t>>, which requires the type parameter to be comparable of type T.

If the incoming list<animal> program will execute normally, because Animal implements the interface comparable<animal>.

However, if the parameter passed in is the List<dog> program will error, because the dog class does not implement interface Comparable<dog> it inherits only one comparable<animal> interface from Animal.

  Note: The animals list actually contains an instance of a dog. If you encounter a similar situation (the subclass list cannot be passed into a method), consider putting the class instance into a parent list to avoid compilation errors.

  3.2 Test for mySort12 (), the main method code is as follows:

 Public Static voidMain (string[] args) {//Create a Animal ListList<animal> animals =NewArraylist<animal>(); Animals.add (NewAnimal (25)); Animals.add (NewDog (35)); //Create a Dog ListList<dog> dogs =NewArraylist<dog>(); Dogs.add (NewDog (5)); Dogs.add (NewDog (18)); //test MySort2 () methodmySort2 (animals); MySort2 (dogs);}

At this time we found that the program can run normally. It can not only accept Animal implements comparable<animal> such parameters, but also receive: Dog implements comparable<animal> such parameters.

3.3 Is it possible to solve the problem by implementing the comparable<dog> of the Dog?  The problem with a program that can be analyzed is that the Dog class does not implement interface Comparable<dog>, so can we implement interface comparable<dog> for this class to solve the problem? The code looks like this:
class extends Implements Comparable<dog>{    public Dog (int.  )        {super  (age);}    }

 The resulting program compiles an error message as follows:

Interface Comparable cannot be implemented more than once with different arguments:comparable<animal> and COMPARABLE<DOG&G T

The meaning is that the dog class has inherited the comparable interface from animal and can no longer implement a comparable.

If a subclass needs to use its own comparison method, it needs to override the public int CompareTo (Animal) method of the parent class.

4. Summary

for Animal/dog The two classes that have a parent-child relationship: <T extends Comparable<? super T>> You can accept List<animal>, or you can receive list<dog>. and <T extends Comparable<T>> only can receive list<animal> so, <t extends comparable<? A type parameter such as Super t>> has fewer restrictions on the parameters passed in, improving the API of flexibility. In general, the least restrictive type parameters are used in order to ensure type safety.

  

  

  

  

Java generics application--t extends Comparable<? Super t>

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.