Generic treatment

Source: Since the collection object can store any type, there is willing to be cast exception occurs when converting so in order to solve this problem provides a mechanism, called generics

Generics: a broad range of types, the type of work ahead of clear data to compile time, learn the characteristics of the array

Generic benefits:

  •   It avoids the problem of type conversion
  •   Yellow warning line may be reduced  
  • We can simplify writing code

When can I use the generic: Q API, when we see such <E>

public  class GenericDeom {
     public  static  void main (String [] args) {
         // create the collection object 
        Collection C = new new the ArrayList ();
         // Create element object 
        Student = S new new Student ( "zhangsan", 18 is ); 
        Student S2 = new new Student ( "Lisi",. 19 );
         // add element object 
        c.add (S); 
        c.add (S2); 
        // traversing a collection of objects 
        the Iterator IT = c.iterator ();
         the while (it.hasNext ()) { 
            String STR =(String)it.next();
            System.out.println(str);
            
            //Student stu=it.next();
            //System.out.println(stu.name);
        }
    }
Exception in thread "main" java.lang.ClassCastException: com.kundada3.Student cannot be cast to java.lang.String
	at com.kundada3.GenericDeom.main(GenericDeom.java:35)

 Reason: added a student, it is wrong to turn to a string

When instantiating a generic class, you must specify the specific type of E

public  class GenericDeom {
     public  static  void main (String [] args) {
         // create the collection object 
        Collection <Student> C = new new the ArrayList <Student> ();
         // Create element object 
        Student = S new new Student ( "zhangsan", 18 is ); 
        Student S2 = new new Student ( "Lisi",. 19 );
         // add element object 
        c.add (S); 
        c.add (S2); 
        // traversing a collection of objects 
        the Iterator <Student> IT = c.iterator () ;
         the while (it.hasNext ()) {
             //STR = String (String) it.next ();
             // System.out.println (STR); 
            
            Student STU = it.next (); 
            System.out.println (stu.name); 
        } 
    } 

} 

class Student { 
    String name; 
    int Age; 
    
    // facilitate the initialization of member variables 
    public Student (String name, int Age) {
         the this .name = name;
         the this .age = Age; 
    } 
}

 

Guess you like

Origin www.cnblogs.com/kun19/p/11074911.html