Generics in Java-based Java

Source: Internet
Author: User

1. Why generics are used

Here we both look at a piece of code;

List List = new ArrayList ();  List.add ("Csdn_seu_cavin");  List.add (+);  for (int i = 0; i < list.size (); i++) {    String name = (string) list.get (i);//When an integer is removed, an exception occurs at run time  System.out.pri Ntln ("Name:" + name);  

This example adds a value of type string and an integer type to the list type collection. (This is legal because the list default type is Object type). In the subsequent loop, the java.lang.ClassCastException exception occurs at run time because the value of the integer type has been added to the list and other reasons have been forgotten. In order to solve this problem, generics emerged.

2, the use of generics

Generics allow programmers to use type abstractions, which are typically used in collections.

list<string> list = new arraylist<string> ();

In this case, the above loop takes a worthwhile approach without an error and does not require a type cast. By LIST<STRING>, directly qualifying elements in the list collection that contain only String types.

3. Generics are only valid during compilation

When we use generics we also have to understand how generics compile, so here we need special attention: generics, only valid when code is compiled into a class file

Ayyaylist<string> a = new arraylist<string> ();  ArrayList B = new ArrayList ();  Class C1 = A.getclass ();  Class C2 = B.getclass ();  

The output of the above program is true. Because all of the reflected operations are performed at run time, since it is true, it proves that the program will take a generic approach after compiling.

This means that generics in Java are only valid during the compilation phase. When a generic result is correctly inspected during compilation, the information about the generic is erased and the method of type checking and type conversion is added at the boundary of the object's entry and exit methods. In other words, a successful compiled class file contains no generic information. Generic information is not entered into the run-time phase .

The following code, through the reflection mechanism of Java, explains very well that generics are only valid during compilation.

Arraylist<string> a = new arraylist<string> ();  A.add ("Csdn_seu_cavin");  Class C = A.getclass ();  try{      method = C.getmethod ("Add", object.class);      Method.invoke (a,100);      System.out.println (a);  [Csdn_seu_cavin, 100]
}catch (Exception e) {
E.printstacktrace ();

  4. Generic classes and generic methods

public static class Fx<t> {      private T ob;//define Generic member variable public        FX (T ob) {          this.ob = ob;      }        Public T Getob () {          return ob;      }        The actual type of public void Showtyep () {          System.out.println ("T" is: "+ ob.getclass (). GetName ());}  }      public static void Main (string[] args) {          fx<integer> Intob = new fx<integer> (+);          Intob.showtyep ();          //java.lang.integer        System.out.println ("----------------------------------");            fx<string> Strob = new Fx<string> ("Csdn_seu_calvin");          Strob.showtyep ();          System.out.println ("value=" + Strob.getob ());  //value=  

  

5. Benefits of Generics

(1) Type safety.

By knowing the type limits of variables defined using generics, the compiler can more effectively increase the type safety of Java programs.

(2) Eliminate forced type conversions.

Eliminate many of the forced type conversions in the source code. This makes the code more readable and reduces the chance of error. All casts are automatic and implicit.

(3) Improve performance

6. Considerations for generics usage

(1) A generic type parameter can only be a class type (including a custom class) and cannot be a simple type.

(2) A generic type parameter can have more than one.

(3) The instanceof operation cannot be used on the exact generic type. If the following operation is illegal, a compile-time error occurs.

(4) You cannot create an array of the exact generic type.

Generics in Java-based 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.