<E> Generics

/ *
* Use custom objects and collections storage traversal
* The collection can store any type of objects, when we store different types of objects, type conversion is likely to occur at the time of abnormal conversion,
* so java To solve this problem, provides us with 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:
* to avoid the type of conversion problem
* can reduce the yellow warning line
* can simplify the writing of our code
*
* when can I use generics?
* Q API, when we see <E>, you can use a generic
*
* /

 

public  class GenericDemo {
     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()) {
            //String str = (String)it.next();
            //System.out.println(str);
            
            Student stu = it.next();
            System.out.println(stu.name+" "+stu.age);
        }
        
        //Student<StringBuilder> st1=new Student<StringBuilder>("张三", 20);
        
        
        
    }
}

class Student {
    String name;
    int age;

    public Student(String name,int age) {
        this.name = name;
        this.age = age;
    }
}

 

Guess you like

Origin www.cnblogs.com/longesang/p/11264485.html