52. Customize generics on methods

Custom generic: A custom generic is a placeholder for a data type or a variable of a data type.

Custom generic:
    modifier <declare custom generic> return value type function name (use custom Generics){
        //code block
    }

For example:
    public <T>String func(T t){     } In the generic type, the basic data type cannot be used. If the basic data type is used, then the wrapper class corresponding to the basic data type is used. Byte Byte short Short int Integer long long double Double float Float boolean Boolean char Character Method generics should pay attention to:     1. Define the generic type on the method, the specific data type of this custom generic type is actually called this method to pass in the data It is determined at the time (that is, what type of data is passed in, what type is it)     2. Custom generics only need to conform to the naming convention of identifiers, but the general habit of custom generics is to use uppercase T and E (T :type E:element) Requirement: Add 1 to all elements in the Integer type collection
    




















public class Demo2 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) {
            System.out.println(add(it.next()));
        }
    }
    
    public static <T>Integer add(T t){
        
        return (Integer)t+1;
    }
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393546&siteId=291194637