Java study note _ 26 _ generic Overview

Source: Internet
Author: User

Generic Overview

The conversion type is required when the objects stored in the container in Java are retrieved, because the objects are converted to the Object type when they are added to the container, and the actual types must be converted during the extraction. However, conversions to lower types are potentially dangerous, so we should avoid them as much as possible.

Java generics:

When defining (classes, methods, parameters, member variables, and so on), generic types are defined as common types, that is, data types can be of any type.

Generics bring great potential to improve the type security and maintenance of large programs.


Objective:

· Strive to convert runtime exceptions to compile errors to reduce the number of runtime exceptions.

· Solve the problem of template programming.

1. generic declaration:

When defining a generic class, define a formal type parameter in <>, for example:

Class TestJava , Class TestList , Class TestVector ,

Where

K: Key, such as the ing key.

V: value, such as the value in Set, List, and Map.

E: exception class.

T: generic.

When instantiating a generic object, you must specify the value of the type parameter after the class name, such:

List List = new ArrayList ():

2. Generic usage:

1> cancel type conversion:

The following is an example of eliminating type conversion:

Import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import java. util. set; public class CollectionsTest {public static void main (String [] args) {// declare the ArrayList object, and the list can only store the List of String-type Elements
 
  
List = new ArrayList
  
   
(); // Add the element list to the array list. add ("1abc"); list. add ("2def"); list. add ("3hij"); list. add ("4klm"); // gets the list element and outputs it without type conversion. out. print ("output fourth element:"); String str = list. get (3); System. out. println (str); System. out. println ("\ n all elements in the output list:"); for (String s: list) {System. out. println (s);} System. out. println (); // declares a HashMap object. The key type is Integer and the value type is StringMap.
   
    
Map = new HashMap
    
     
(); // Add the element map to the object. put (1, "zhao"); map. put (2, "qian"); map. put (3, "sun"); map. put (4, "li"); // get the key Set
     
      
Keys = map. keySet (); // obtain the corresponding value from the key and output the System. out. println ("output: key = value"); for (Integer I: keys) {String value = map. get (I); System. out. println (I + "=" + value );}}}
     
    
   
  
 

Output result:

Output the fourth element: 4klm

All elements in the output list:

1abc

2def

3hij

4klm

Output: key = value

1 = zhao

2 = qian

3 = sun

4 = li

Note:

· The generic type is not specified when the set is used in the attribute. The default value is, Such as defining attributes: ListList = null;

· Different generic references cannot be assigned values to each other.

· The object type added to the set must be consistent with the specified generic type.

2> restrict the use of type parameters in generics:

· : Allows all generic reference calls.

· : Only reference calls with the wildcard Number and Number subclass are allowed.

· : Only reference calls with the wildcard Number and Number parent classes are allowed.

· : Only generic calls are allowed to reference the implementation classes that implement the Comparable interface.

Note:

· When a set is used in method parameters, the default generic type is not specified. .

· In method parameters This modifier is not supported.

The following example shows the parameter range of the restricted type:

Import java. util. ArrayList; import java. util. List; public class CollectionsTest {public static void main (String [] args) {List
    
     
L1 = new ArrayList
     
      
(); L1.add ("China"); List
      L2 = new ArrayList(); L2.add (99); List
        
         
L3 = new ArrayList
         
           (); L3.add (3.3); List
          
            L4 = new ArrayList
           
             (); L4.add (83); List
            
              L5 = new ArrayList
             
               (); L5.add (93.67); printView (l1); // String-type generic Object printView (l2); // the Object-type generic Object printView (l3 ); // Number type generic object printView (l4); // Integer type generic object printView (l5 ); // Double type generic object} // when the set is used in method parameters, the generic type is not specified. The default value is
              @ SuppressWarnings ("rawtypes") private static void printView (List list) {for (Object o: list) {System. out. println (o );}}}
              

Output result:

China

99

3.3

83

93.67

(1) When the method in the preceding example changes:

// Allow all generic references to call @ SuppressWarnings ("rawtypes") private static void printView (List
               List) {for (Object o: list) {System. out. println (o );}}

,Output result:

China

99

3.3

83

93.67

The output result remains unchanged.

(2) When the method in the preceding example changes:

// Allow reference calls of the Number and Number self-classes @ SuppressWarnings ("rawtypes") private static void printView (List
               List) {for (Object o: list) {System. out. println (o );}}

Note the following two lines:

// PrintView (l1); // String-type generic Object // printView (l2); // Object-type generic Object

Run,

Output result:

3.3

83

93.67

(3) When the method in the preceding example changes:

// Only supports reference calls for classes that implement the Comparable interface @ SuppressWarnings ("rawtypes") private static void printView (List
               List) {for (Object o: list) {System. out. println (o );}}

Note the following two lines:

// PrintView (l2); // generic Object of the Object type // printView (l3); // Number-type generic Object

Run,

Output result:

China

83

93.67

(4) the method in the preceding example is changed:

// Only allow reference calls of the Number and Number parent classes @ SuppressWarnings ("rawtypes") private static void printView (List
               List) {for (Object o: list) {System. out. println (o );}}

Note the following three lines:

// PrintView (l1); // String-type generic object // printView (l4); // Integer-type generic object // printView (l5 ); // Double type generic object

Run,

Output result:

99

3.3

3> generic methods (also known as polymorphism in Java ):

Add a list of formal type parameters to the class definition to make the class generic. Methods can also be generic, regardless of whether their classes are generic or not.

The format of the generic method is:

Exception thrown by the parameter table of the Method Name of the generic return type Modifier

There are several generic styles:

· : Allows generic reference calls.

· : Only reference calls with the wildcard Number and Number subclass are allowed.

· : Only generic calls are allowed to reference the implementation classes that implement the Comparable interface.

· : Allows only the Number and Number sub-classes of the generic type to implement the Comparable interfaces.

Implementation class reference call.

Note: In the generic method This modifier is not supported.

The following is an example of using generic methods:

Import java. util. ArrayList; import java. util. List; public class CollectionsTest {public static void main (String [] args) {// declare a List of various objects
               
                
L1 = new ArrayList
                
                 
(); List
                 L2 = new ArrayList(); List
                   
                    
L3 = new ArrayList
                    
                      (); List
                     
                       L4 = new ArrayList
                      
                        (); List
                       
                         L5 = new ArrayList
                        
                          (); // Create various Arrays: String [] a1 = new String [1]; a1 [0] = "a1"; Object [] a2 = new Object [1]; a2 [0] = "Object"; Number [] a3 = new Number [1]; a3 [0] = 3; Integer [] a4 = new Integer [1]; a4 [0] = 4; Double [] a5 = new Double [1]; a5 [0] = 5.5; // copy an array of the same type to the object copyFromArray (l1, a1); copyFromArray (l2, a2); copyFromArray (l3, a3); copyFromArray (l4, a4); copyFromArray (l5, a5 ); // display the object element printView (l1); printView (l2); printView (l3); printView (l4); printView (l5 );} // display method private static void printView (List
                         L) {for (Object o: l) {System. out. println (o) ;}// copy method private static
                         
                           Void copyFromArray (List
                          
                            L, T [] a) {for (T o: a) l. add (o );}}
                           

Output result:
A1

Object

3

4

5.5

4> generic classes:

Writing of generic classes:

class Person
                            
                              {public void show(E e) {System.out.println(e);}public E get() {return null;} }
                            

Note the following when writing generic classes:

·The generic type of the class cannot be used in static methods because the generic type in the generic class is replaced with a definite type when creating the class object.

Static methods can be directly accessed through class names, while Java is a strong class language, and no type variables or objects are allowed to exist,

Therefore, generic classes cannot be used in static methods.

·Do not create a generic class object, because a generic class may be an interface or abstract class, and can be created if it is not an interface or abstract class.

·The generic type cannot be used in Catch clauses, because if the try clause throws an exception of a check during compilation, the compiler cannot determine whether the Catch exception can survive.

The following is an example of how to create a generic class:

Code in TestGenrics:

public class TestGenrics {public static void main(String[] args) {@SuppressWarnings({ "rawtypes" })MyClass
                             test = new MyClass();test.show();MyClass
                            
                              str = new MyClass
                             
                              ();str.method("323");str.show();MyClass
                              
                                i = new MyClass
                               
                                ();i.method(323);i.show();} } 
                               
                              
                             
                            

Generic MyClass Code in:

 class MyClass
                            
                              {private T t;public void method(T t) {this.t = t;}public T method1() {return null;}public void show(){System.out.println(t);} }
                            

Output result:

Null

323

323

















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.