53. Generic classes

Generic class definition format:
    class class name <declare custom generic type>{
    
    }

Notes for generic class:
    1. The specific data type of the custom generic type on the class is to create the object when the class is used
    2. If a class has declared a custom generic type on the class, if the specific data type of the generic type is not specified when using the class to create an object, the default is Object type 3.
    If the custom generic type is used in the class It cannot be used for static methods. If the static method needs to use a custom generic type, then you must declare the usage
        instructions yourself: the static method can be called directly without instantiation, and the data type of the generic class is declared at the time of declaration. OK,
        so static methods need to define and declare custom generics themselves

 

Requirement: All set elements of integer type are incremented by 1

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

 

Guess you like

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