定义泛型接口和类

JDK1.5之后的List接口,Iterator接口,Map接口的代码:

public interfaceList<E>

{

         voidadd(E x);

         Iterator<E> iterator();

}

public interfaceIterator<E>

{

          E next();

          Boolean hasNext();

}

Public interfaceMap<K,V>

{

           Set<K> keyset();

           V put(K key, V value);

}

上面三个接口声明比较简单,除了尖括号中的内容――这就是泛型的实质;允许在定义接口,类时指定类型形参,类型形参在整个接口,类体内中可当作类型使用,几乎所有可使用其他普通类型的地方都可以使用这种类型形参。

例如我们使用List类型时,为E形参传入String类型实参,则产生了一个新的类型: List<String>类型,我们可以把List<String>想像成E杯全部替换成String的特殊List子接口:

Public interfaceListString extends List

{

           Voidadd(String x);

           Iterator<String> iterator();

}

虽然程序只定义了一个List<E>接口,但实际使用时可以产生无数多个List接口,只要为E传入不同的类型实参,系统就会多出一个新的List子接口。

public class Apple<T> {

      private T info;

      public Apple(){}

      public Apple(T info){

        this.info =info;

      }

      public void setInfo(T info){

        this.info =info;

      }

      public T getInfo(){

        return this.info;

      }

     

      public static void main(String[] args){

        Apple<String> a1 = new Apple<String>("Apple");

        System.out.println(a1.getInfo());

        Apple<Double> a2 = new Apple<Double>(2.00);

        System.out.println(a2.getInfo());

      }

}

Output:

Apple

2.0

上面定义了一个带泛型声明的Apple<T>类,实际使用时会为T形参传入实际类型。

原文地址:https://www.cnblogs.com/snake-hand/p/3180156.html