54. 泛型接口

泛型接口的定义格式:
    interface 接口名<声明自定义泛型>{
        
    }

泛型接口要注意的事项:
    1.接口上自定义泛型的具体数据类型是在实现一个接口的时候指定的
    2.在接口自定义的泛型如果在实现接口的时候没有指定具体的数据类型,那么默认为Object类型

如果我们在实现接口的时候,任然不明确自己目前要操作的数据类型,我要等到创建实现类的时候指定数据类型。
延长接口自定义泛型的具体数据类型格式:
    class 类名<声明自定义泛型> implements 接口名<声明自定义泛型>{
    
    }

例如:
    class Demo1<T> implements Dao<T>{
    
    }

需求:把Integer类型集合中的元素全部加1

//定义泛型接口
interface AddInterface<T>{
    public Integer add(T t);
}

//实现类
class Math1<T> implements AddInterface<T>{

    @Override
    public Integer add(T t) {
        return (Integer)t+1;
    }
}
public class Demo4 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        Iterator<Integer> it = list.iterator();
        //实例化实现类
        Math1<Integer> m = new Math1<Integer>();
        while(it.hasNext()) {
            System.out.println(m.add(it.next()));
        }
    }
}

原文地址:https://www.cnblogs.com/zjdbk/p/8999155.html