Java: Generic

Source: Internet
Author: User

Java: Generic

If there is no generic type, parameters can be "arbitrary" by referencing the type Object. The disadvantage of "arbitrary" is explicit forced type conversion, this type of conversion requires developers to make predictions about the actual parameter type. If the forced type conversion is incorrect, the compiler may not prompt an error and the exception occurs during running. This is a security risk. The advantage of generics is to check the type security during compilation, and all the forced conversions are both automatic and implicit, improving the code reuse rate.

Example 1: General Knowledge

① Define a Student class

public class Student {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
② Define the Test class

Import java. util. arrayList; import java. util. list; public class Test {public static void main (String [] args) {// The method stubs automatically generated by TODO Student student1 = new Student (); student1.setName ("leelit "); student student2 = new Student (); student2.setName ("lina"); ListList1 = new ArrayList <> (); list1.add (student1); list1.add (student2); System. out. println (Student) list1.get (0 )). getName (); System. out. println (list1.get (1); // must cast to (Student) List
  
   
List2 = new ArrayList <> (); list2.add (student1); list2.add (student2); System. out. println (list2.get (0 ). getName (); System. out. println (list2.get (1 ). getName ());}}Print result:
   

leelitStudent@1db9742leelitlina

The comment of the Test class also shows that the function of the generic type is to check the type security during compilation, and all the forced conversions are both automatic and implicit, if the Object class is used for implementation, explicit type conversion is required.


Example 2: Custom generic

① Define a Student class

public class Student {private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
② Define a generic

public class Generic
    
      {T obj;public T getObj() {return obj;}public void setObj(T obj) {this.obj = obj;}}
    
③ Define the second generic

public class Generic2
    
      {private T obj1;private P obj2;public T getObj1() {return obj1;}public void setObj1(T obj1) {this.obj1 = obj1;}public P getObj2() {return obj2;}public void setObj2(P obj2) {this.obj2 = obj2;}}
    
④ Test class

Public class Test {public static void main (String [] args) {// The method stub generated automatically by TODO // The Generic parameter is set to the String class Generic
    
     
Generic = new Generic <> (); generic. setObj ("hello"); System. out. println (generic. getObj (); // set the generic parameter to Student student = new Student (); student. setName ("leelit"); student. setAge (21); Generic
     
      
Generic1 = new Generic <> (); generic1.setObj (student); System. out. println (generic1.getObj (). getName () + "" + generic1.getObj (). getAge (); // There are two generic parameters: Generic2
      
       
Generic2 = new Generic2 <> (); generic2.setObj1 (student); generic2.setObj2 (new Double (99.9); System. out. println (generic2.getObj1 (). getName () + "" + generic2.getObj1 (). getName () + "" + generic2.getObj2 ());}}
      
     
    
Print result:

helloleelit 21leelit leelit 99.9
Example:

1. generic type parameters can only be classes, not simple types.
2. There can be multiple generic type parameters.

Example 3: bounded type, wildcard type, and generic method. (The text part of this article is mainly from Baidu encyclopedia. The following example is also used)

① Define a bounded generic type

Import java. util. Collection; public class CollectionGenFoo
    
     
{// The generic T in such a class can only be the implementation class of the Collection interface. If it is not an interface, it is the current class or the inheritance class private T x; public CollectionGenFoo (T x) {this. x = x;} public T getX () {return x;} public void setX (T x) {this. x = x ;}}
    
② Test class

Import java. util. arrayList; import java. util. collection; public class Test {public static void main (String args []) {CollectionGenFoo listFoo = null; listFoo = new CollectionGenFoo (new ArrayList (); // error, do not do this. // CollectionGenFoo
    
     
ListFoo1 = null; // listFoo1 = new CollectionGenFoo (new ArrayList (); System. out. println ("instantiation successful! "); Test test = new Test (); test. f (test); test. f (" "); test. f (" ", 5);} public
     
      
Void f (T x) {// generic method System. out. println (x. getClass (). getName ();} public
      
       
Void f (T x, P y) {// The generic method has two parameters: System. out. println (x. getClass (). getName () + "" + y. getClass (). getName ());}}
      
     
    
Print result:

Instantiated successfully! Testjava. lang. Stringjava. lang. String java. lang. Integer

Whether a generic method exists. It has nothing to do with whether the class is generic. To define a generic method, you only need to place the list of generic parameters before the return value.


③ Redefine a Test wildcard.

To solve the problem that the type cannot be determined dynamically based on the instance when it is restricted, the wildcard is introduced. For the above example, the wildcard format is , "?" Represents the unknown type, which is the Collection interface.

Public class Test {public static void main (String args []) {CollectionGenFoo listFoo = null; listFoo = new CollectionGenFoo (new ArrayList (); // currently, CollectionGenFoo is not faulty.
    ListFoo1 = null; listFoo1 = new CollectionGenFoo (new ArrayList (); System. out. println ("instantiation successful! ");}}

1. If only Without extends, the Object and any Java classes under it are allowed by default. That is, any class.
2. wildcard generics are not limited downward, as shown in figure , You can also raise the limit, such , Indicates that the type can only accept Double and its upper parent class types, such as Number and Object type instances.


Summary: The advantage of generics is to check the type security during compilation, and all mandatory conversions are both automatic and implicit, improving the code reuse rate.










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.