Ten: Generics of Java

Source: Internet
Author: User


Custom

One, the definition of generics mainly have the following two kinds:

Some types that include type parameters in program encoding, that is, generic parameters can only represent classes. Cannot represent individual objects. (This is the more common definition of today)

Some classes that include the number of parameters in the program encoding. Its parameters can represent classes or objects, and so on.

(Nowadays most people call this a template)

Regardless of the definition used. The parameters of generics must be specified when they are actually used.

generic class. is to specify the detail type of the generic when instantiating the class.

Generic method. is to indicate the verbose type of the generic when calling the method.

Second, the purpose of using generics:

Some strongly-typed programming languages support generics, whose main purpose is to enhance type safety and reduce the number of class conversions, but some programming languages that support generics can only achieve some purpose.

Generic programming (genericprogramming) means that the code you write can be reused by very many different types of objects.

is an extension of the type system of the Java language to support the creation of classes that can be parameterized by type. The ability to think of type parameters as a placeholder for the type specified when using the type of the parameter. Just as the form parameter of a method is a worthy placeholder passed at execution time.

"Several types of Java generics code"

I. Code that does not use generics

We define a person class, including three attribute X. Y,z. When we start defining, we don't know what these three properties are for, so we're defining the object type.

But when it comes to use, we're on X. Y. Z gives the int,double. String type, so at the time of removal. We need to cast these three types of values. For example, the following code:

1. Person.java


<span style= "FONT-SIZE:18PX;"     > public class Person {private Object x;     Private Object y;      Private Object Z; Use the object type.      Can be converted to whatever type public Object GetX () {return x;    } public void SetX (Object x) {this.x = x;    } public Object GetY () {return y;    } public void Sety (Object y) {this.y = y;    } public Object GetZ () {return z;    } public void Setz (Object z) {this.z = Z; }}2. Nogenerictest.java public class Nogenerictest {public static void main (String[]args) {person Boy=new person (         );         Boy.setx (20);         Boy.sety (22.2);         Boy.setz ("Guy tt"); Depending on the different types of values set, we need to make a forced type conversion.

int x= (Integer) boy.getx (); Double y= (double) boy.gety (); String z= (String) Boy.getz (); SYSTEM.OUT.PRINTLN (x); System.out.println (y); System.out.println (z); }}3. Executive results 20 22.2 handsome tt</span>

Ii. code that uses a generic type variable

We define a generic class person, define three properties x, Y, Z, and in the test class, we set the value of the property and print it.

<span style= "FONT-SIZE:18PX;" > 1.     Person.java public class Person<t> {private T x;    Private T y;     Private T-Z;      Public T GetX () {return x;    } public void SetX (T x) {this.x = x;    } public T GetY () {return y;    } public void Sety (T y) {this.y = y;    } public T GetZ () {return z;    } public void Setz (T z) {this.z = Z; }}2.         Generictest.java public class Generictest {public static void main (String[]args) {person boy=new person ();         Boy.setx (20);         Boy.sety (22.2);         Boy.setz ("Guy tt");         No type conversion System.out.println (BOY.GETX ()) is necessary;        System.out.println (Boy.gety ());    System.out.println (Boy.getz ()); }}3. Execution results 2022.2 handsome guy TT three, using two types of variable generic code we define a generic class person, define two attributes X, Y. Two different types of variables are used in the test class. We set the value of the property. and print.     1. Person.java public class Person<t1,t2> {private T1 x;     Private T2 y;      Public T1 GetX () {return x; } PUBlic void SetX (T1 x) {this.x = x;    } public T2 GetY () {return y;    } public void Sety (T2 y) {this.y = y; }}2. Generictest.java public class Generrictest {public static void main (string[] args) {person<string,integer& Gt         Boy=new person<string,integer> ();         Boy.setx ("Guy tt");         Boy.sety (20);        System.out.println (Boy.getx ());      System.out.println (Boy.gety ()); }} 3. Executive Results Handsome TT 20</span>


Iv. Inheritance using generics


We define a generic class person, which defines two attribute x. Y, and then define a generic class boy. Defines the attribute Z. Boy inherits the person class, and in the test class, we set the value of the property. and print.

1. Person.java public class Person<t1,t2> {private T1 x;     Private T2 y;      Public T1 GetX () {return x;      } public void SetX (T1 x) {this.x = x;    } public T2 GetY () {return y;    } public void Sety (T2 y) {this.y = y; }} 2.    Boy public class Boy<t1,t2,t3>extendsperson<t1,t2> {private T3 z;    Public T3 GetZ () {return z;    } public void Setz (T3 z) {this.z = Z; }}3. Generictest.java 1public class Generictest {2 public static void Main (string[] args) {3 Boy<string,integer, Double> boy=new boy<string,integer,double> (); 4 Boy.setx ("Guy tt"); 5 boy.sety (20); 6 Boy.setz (200000.22); 7 8 System.out.println (Boy.getx ()); 9 System.out.println (Boy.gety ()); System.out.println (Boy.getz ()); 11}12} 4. Execution result 1 handsome man TT2 203 200000.22

V. Interfaces that use generics

We define a generic interface person, define two methods, and then define a generic class boy that implements a generic interface person. Define attributes x, Y, Z, in the test class. We set the value of the property and print it.


<span style= "FONT-SIZE:18PX;" >1. PERSON.JAVA1 public interface Person<t1,t2> {2 public T1 GetX (), 3 public T2 GetY (); 4} 2. Boy 1public class Boy<t1,t2,t3>implements person<t1,t2> {2 private T1 x; 3 private T2 y; 4 private T 3 Z; 5 public T1 GetX () {6 return x; 7} 8 public void SetX (T1 x) {9 this.x = x;10}11 public T        2 GetY () {y;13}14 public void sety (T2 y) {$ this.y = y;16}17 public T3 GetZ () {18 return z;19}20 public void Setz (T3 z) {this.z = z;22}2324}3. Generictest.java 1public class Generictest {2 public static void Main (string[] args) {3 Boy<string,integer, Double> boy=newboy<string,integer,double> (); 4 Boy.setx ("Guy tt"); 5 boy.sety (20); 6 Boy.setz (200000.22); 7 System.out.println (Boy.getx ()); 8 System.out.println (Boy.gety ()); 9 System.out.println (Boy.getz ()); 10}11}4. Executive Results 1 HandsomeBrother TT2 203 200000.22</span> 


Vi. using generic methods

Explain. When defining a generic method, you must add a <T> to the front of the return value. To declare that this is a generic method, hold a generic t, and then have the ability to use the generic T as the return value of the method.

Define a normal class person and define a generic method, such as the following code:

<span style= "FONT-SIZE:18PX;" >1. Person.java 1public class person{2 public    static<t>t Getmiddle (t[]a) {3        return A[A.LENGTH/2]; 4     } 5< C3/>public static void Main (string [] args) {6        string[]name={"Guy tt", "Handsome TT1", "Handsome TT2"}; 7        String Middle=person. <string>getmiddle (name); 8        System.out.println (middle), 9        integer[]num={20,22,25};11        Integer Middle1=person.<integer >getmiddle (num);        System.out.println (Middle1);        double[]num1={20.0,22.2,25.5};15        Double Middle2=person.<double>getmiddle (NUM1),        System.out.println (middle2),}18}2    . Executive Results 1 handsome TT12 223 22.2</span>


The limitation of type variable

For example, in the following code, we define a variable smallest type T in method Min. This shows that smallest can be any class object, we need to use the CompareTo method in the following code, but we have no way to determine that our T contains CompareTo method, so we need to define T, In the code we let T inherit the comparable class.

For example, the following:

<span style= "FONT-SIZE:18PX;" >public static<t extendscomparable>t min (t[]a)   1.person.java 1public class person{2 public    static <t extends Comparable>t min (t[]a) {3        if (a==null| | a.length==0) {4            return null; 5        } 6        T smallest=a[0]; 7 for        (int i=1;i<a.length;i++) {8            if ( Smallest.compareto (A[i]) >0) {9                 smallest=a[i];10             }11        }12        return smallest;13    }14    public static void Main (String [] args) {        integer[]num={20,25,30,10};16        Integer Middle=person.<integer >min (num);        System.out.println (middle);    }19} 2. Execution result 10</span>


"Java Generic Understanding"


First, type erase

The first prerequisite for a proper understanding of the generic concept is to understand type erasure (type erasure). Generics in Java are basically implemented at the compiler level.

The type information in the generic is not included in the generated Java byte code. When a generic is used, the type parameters that are added are removed by the compiler at compile time. This process is called type erasure. Types such as list<object> and list<string>, as defined in the code. It becomes a list after compilation. The JVM sees only the list, and the type information appended by generics is not visible to the JVM. The Java compiler will try to identify possible errors at compile time, but there is still no way to avoid the case of a type conversion exception at execution time.


The odd features of very many generics are related to the existence of this type of erasure, including:

A generic class does not have its own unique class object. For example, there is no list<string>.class or list<integer>.class, but only list.class.

Static variables are shared by all instances of the generic class. For classes declared as Myclass<t>, the method of visiting static variables is still myclass.mystaticvar.

Whether you create an object through new myclass<string> or new myclass<integer>, you are sharing a static variable.

Generic type parameters cannot be used in a catch statement for Java exception handling.

Because exception handling is performed by the JVM at the time of execution. Because the type information is erased, the JVM cannot differentiate between the two exception types Myexception<string> and myexception<integer>. For the JVM, they are all myexception types. The catch statement corresponding to the exception cannot be executed.

Ii. Best Practices

There are some key principles that can be followed when generics are used. To avoid some common problems.

Avoid mixing generic classes and primitive types in your code. For example, list<string> and list should not be used together. This produces some compiler warnings and potential execution-time exceptions. When you have to take advantage of legacy code developed prior to JDK 5 and have to do so, isolate the relevant code as much as possible.

When using generic classes with wildcard characters, you need to understand the concept of a set of types represented by wildcards. Because the detailed type is unknown, very many operations are not agreed.

Generic classes are best not to be used with arrays. You can only create this array of new LIST<?>[10]. Cannot create new list<string>[10] this. This limits the ability of the array to be used. And it brings up a lot of puzzling questions. Therefore, when you need an array-like function, you can use the collection class.

Do not ignore the warning messages given by the compiler.


Ten: Generics of 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.