再识Java泛型

来源:互联网 发布:聚划算淘宝商城特价区 编辑:程序博客网 时间:2024/05/29 13:23

*构造方法中使用泛型:*和正常构造方法没什么不同
代码示例:

class A<T>{private T x;public A(T x){        this.x=x;    }}

设置多个泛型:在尖括号中设置多个泛型,用逗号隔开就行
一般设置两个,用

package genericDemo;class A<T>{    private T x;    public T getX() {        return x;    }    public void setX(T x) {        this.x = x;    }   }public class genericDemo02 {    public static void main(String[] args) {        A<Integer> a=new A<Integer>();        a.setX(10);        show(a);    }//这种用法会报错   //  public static void show(A<Object> a) {//      System.out.println(a.getX());//  }//  Exception in thread "main" java.lang.Error: Unresolved compilation problem: //  The method show(A<Object>) in the type genericDemo02 is not applicable for the arguments (A<Integer>)//这种用法会有警告,不安全//  public static void show(A a) {//      System.out.println(a.getX());//  }//  //这是使用通配符,最好的方案    public static void show(A<?> a) {        System.out.println(a.getX());    }}

泛型接口:和泛型类几乎一样,比较简单,不作代码演示

泛型方法:泛型方法中可以定义泛型返回值;泛型方法中可以定义泛型参数,参数类型就是调用时传入数据类型
格式:访问权限 <泛型标识>泛型标识 方法名称 ([泛型标识,参数名称] )
代码示例如下:

package genericDemo;class B{    public <T>T show(T t){        return t;    }}public class GenericDemo {    public static void main(String[] args) {        B b=new B();        int x=b.show(1);        System.out.println(x);    }}

泛型数组:一般和泛型方法搭配使用
代码演示如下:

package genericDemo;public class GenericDemo03 {    public static void main(String[] args) {        // TODO Auto-generated method stub        String arr[]= {"hello","world","hi"};        show(arr);        Integer arr1[]= {1,2,3,4,5};        show(arr1);    }    public static <T>void show(T arr[]){        for(int i=0;i<arr.length;i++)            System.out.println(arr[i]);    }}
原创粉丝点击