The understanding of generics in Java

Source: Internet
Author: User

Generics in Java, essentially, are parameterized types, meaning that the data type being manipulated is specified as a parameter rather than a certain type. This data type can be used in classes, interfaces, and method creation. That is, generic class, generic interface, generic method. That may not be vivid enough to give some examples.

Example One

Let's take a simple look at the generic scenario using example one . In the following scenario, generics are not used:

 Public classFanxingtest { Public Static voidMain (string[] args) {ArrayList ArrayList=NewArrayList (); Integer Integer1= 1;        Arraylist.add (Integer1); //you remember the type of this element, so no problem, take it out by indexInteger integer2 = (integer) arraylist.get (0);        System.out.println (INTEGER2); //If you remember the wrong type of ArrayList, then the compiler will not error, but the operation will be errorString string = (string) arraylist.get (0);    System.out.println (string); }}

the object class is stored in the ArrayList. The benefit is that the implementation of a reference to type object can hold any class (the polymorphic mechanism of Java), but it also presents a disadvantage: Forced type conversions are required.

As you can see, in the absence of generics, if you remember what kind of things are stored in the arrayList , then it is best that you can go directly to the index to take out, and type conversion can be.

And if you do not know the case of forced conversion, the compiler will not prompt the error, at run time will be found, will report a mistake: Java.lang.ClassCastException:java.lang.Integer cannot be cast to Java.lang.String . In practice, it is not possible for programmers to remember the type of each element, so there is a clear irrationality.

The introduction of generics solves the above problems by first looking at the use of generics for this scenario:

 Public classFanxingtest { Public Static voidMain (string[] args) {ArrayList<Integer> arrayList =NewArraylist<integer>(); Integer Integer1= 1;        Arraylist.add (Integer1); //directly removed without forcing the type conversionInteger integer2 = arraylist.get (0);        System.out.println (INTEGER2); //The compiler will check for errors and not allow you to confuse the type, the following two scenarios the compiler will directly prompt the type conversionString string1 = (string) arraylist.get (0); String string2= Arraylist.get (0); }}

In the above code we used generics, that is, when creating arrayList , it is limited to the only Integer type of data stored inside, then compile can check type safety, all forced type conversion is automatic and implicit, Increase the rate of code reuse. When we take out the data, we don't have to cast the coercion, and if you mistake the type, the compiler will prompt the error.

Example Two

So how is generics implemented? How do you create a generic class? Let's take a look at example two . First, create a generic class yourself, as follows:

//Create a new generic class yourself: MyfanclassMyfan<t>{    PrivateT T1; //constructor Function     PublicMyfan (T t1) { This. t1=T1; }    //to test the operation data type of a generic type     Public voidShowinfo () {System.out.println ("The data type being manipulated is:" +T1.getclass (). GetName ()); //through the reflection mechanism, we can know the information of various member variables and methods of T.Method m[]=T1.getclass (). Getdeclaredmethods ();  for(inti = 0; i < m.length; i++) {System.out.println (M[i].getname ()); }    }}

when creating a generic class yourself, let's assume a situation where I want my class to handle multiple types of data. This requires the "parameterization" of the type, which is a "parameter" to be passed in. So when defining a class, the class name is followed by a <T>: class myfan<t> , this T is just a symbolic symbol, can be any symbol. T is a type "parameter" and we can then pass in any type of class. In the Showinfo () method above, we can use the reflection mechanism to get the data type that is passed in, and we can get some methods in this class. Next, we'll experiment with the generic class myfan<t> we created:

 Public classFanxingtest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubMyfan<String> ft1=NewMyfan<string> ("Yellow yellow");        Ft1.showinfo (); Myfan<Integer> ft2=NewMyfan<integer> (1);        Ft2.showinfo (); //output Two instance object type, the result is the sameSystem.out.println (Ft1.getclass ());    System.out.println (Ft2.getclass ()); }}

By creating an instance of our own generic class, the T1 variable in ft1 points to a string class instance, and the T1 variable inside the ft2 points to an instance of an integer class. Then the output of the above program is as follows:

The operating data type is: java.lang.String
... The individual member methods of string omit the operating data type: Java.lang.Integer
... The individual member methods of integer omit class Myfanclass Myfan

The last two lines of output, we want to see through the Ft1/ft2.getclass () to look at the creation of these two instances of the type will not be the same, the result can be seen, two are belong to the Myfan class instance variable, are not different due to the type of incoming.

example Three

Now you should know how generics work, and when we define a generic class or generic interface, the,<t> is followed by the class name: myfan<t>{...} , and then instantiating < T> is also followed by the class name: myfan<t> fan1 = new myfan (); .

There are times when we encounter more complicated situations, and these days I see the Sort method in the tool collections, as follows:

1  Public Static void Sort (list<t> List) {2         list.sort (null); 3     }

we need to know that the type behind the extends represents the upper bound of the generic (including itself), and super represents the lower bound of the generic (including itself). such as the <t extends class/interface, which means T must be a subclass of the specified class/interface (implements an interface or inherits from a class, counts "subclasses").

Let's see  <t extends comparable<? super T>>   first stipulates that T must be  COMPARABLE<? super T> a subclass of  , that is to say, T must be implemented  COMPARABLE<? super T>   of this interface. Then <? Super t> means that the lower bound of the type in comparable<> is T (or at least the parent class of T, including T)! We can use  gregoriancalendar   and     class to deepen understanding. Let's take a look at the definition of two classes:

 // public  abstract  class  Calendar implements  Serializable, cloneable, comparable< Calendar>{... @Override  public  int   CompareTo (Calendar Anothercalendar) { return   CompareTo (getmillisof (Anothercalendar)); }}  // gregoriancalendar class inherits from the Calendar class  public  class  GregorianCalendar extends  calendar{...} 

So we now assume that there is a ArrayList that calls the sort method above:

New Arraylist<gregoriancalendar>(); Collections.sort (arrayList);

At this time will not error, because the equivalent of <gregoriancalendar extends comparable<calendar>> is established, We can know by combining the definitions of two classes: The calendar is the parent of GregorianCalendar, and the calendar implements Comparable<calendar> so GregorianCalendar The Comparable<calendar> interface is also implemented. So the scope of the generic limit <t extends comparable< Super The t>> is satisfied. Next we define a sort function ourselves:

 Public Static extends void Sort (arraylist<t> list) {    list.sort (null);}

now call our sort function sort (new arraylist<gregoriancalendar> ()); , the compiler will make an error because the GregorianCalendar class simply implements the Comparable<calendar> interface and does not implement the Comparable<gregoriancalendar> interface. So the incoming parameter does not meet the scope of the generic limit, so it will be error -

some of their own thinking

Let's take a look at the two sort methods in the following collections class

 Public Static extends Super void Sort (list<t> List) {    list.sort (null);}  Public Static void Super T> c) {    list.sort (c);}

Notice that in addition to the method parameters (such as the list<t> list) above, it is the label before the return type (void) (such as the static <t extends Comparable< Super t>> Void).

In fact, the generic is "dispensable", its existence is to limit the parameters you will be using the class is what range, Extends/super is the generic upper and lower bounds (inclusive). For example, the first sort above, limits the <t extends Comparable< Super T>> the second one is not qualified, arbitrary <T>; but there are parameters of this block, the first parameter is the previously qualified parameter T can be, the second parameter, in COMPARATOR< Super T> here defines a next term, which has to be the parent class of T.

further down, why is <t extends Comparable<, Super t>> instead of <t extends comparable<t>>? This actually takes into account that if the subclass inherits from the parent class, and the parent class has implemented the comparable interface, the subclass can be used, so there is <t extends Comparable<. The super t>> effect, for example, is the above GregorianCalendar class and the Calendar class, equivalent to subclass GregorianCalendar also implements the comparable interface. At this time if <t extends comparable<t>> is not suitable.

in fact, the general self-realization of the comparable interface, are class MyTest implements comparable<mytest> this, it is estimated that class MyTest implements The father of Comparable<mytest, the above <t extends comparable< Super t>> just take into account such as manmantest inherit from MyTest, then manmantest also realized the situation of Comparable<mytest> interface .

The understanding of generics 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.