Senior Java - Generics

This paper describes the use of generics

1, used in the collection

2, generic class, generic interfaces, generic method Custom

3, the relationship between generics and inheritance

4, Tsuhaifu

Since the first and second points are skilled in the usual coding herein focuses on two later.

Directly show the code:

package com.learn;

import java.util.List;

public class ParentGeneric<T> {
    private String name;
    
    private int id;
    
    private T t;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public T getT() {
        return t;
    }
    
    public void setT(T t) {
        this.t = t;
    }
    
    // 声明泛型方法-单个
    public <E> E getE(E e) {
        E return; 
 * as: public class StudentDAO extends AbstractDAO <Student > { } internal CRUD methods
    } 
    
    // declare a generic method - a plurality of 
    public <E> E [] getArray (E [] ARR) { 
        return ARR; 
    } 
    
    // declare a generic method - interactive 
    public <E> void fromArrayToList (E [] arrayE, List <E> Liste) { 
        for (E E: arrayE) { 
            listE.add (E); 
        } 
    } 
    
    @Override 
    public String toString () { 
        return "ParentGeneric [name =" + name + ", ID =" + + ID " , T = "+ T +"] "; 
    } 
    
} 

/ * 
 * when inherited generic class or interface, can be named generic type 
 * 
 * DAO usually treated when using generic type named (that is, a generic Object Access the Data) 
 * Similarly: public class TeacherDAO extends AbstractDAO <Teacher >Internal CRUD methods {} 
 * 
 * Source Analysis: Learning generic method
 * public interface Collection<E> extends Iterable<E> {
 *      <T> T[] toArray(T[] a);
 * }
 * 
 */

class SonOneGeneric<T> extends ParentGeneric<T> {
    
}

class SonTwoGeneric extends ParentGeneric<Integer> {
    
}

  

Guess you like

Origin www.cnblogs.com/gzhcsu/p/11703389.html