尔游网
您的当前位置:首页6、泛型

6、泛型

来源:尔游网

泛型

1、  泛型可以在函数使用时才确定数据类型,而不是在声明时就确定数据类型,这样大大提高了函数的灵活性和数据类型的安全性,如下

//<T>即为泛型,在定义时将类型作为参数

//不需要为各个类型的数据各自开发功能

class Point<T>{

    private T x;

    private T y;

    public Point(T x, T y){

        this.x = x;

        this.y = y;

    }

    public T getX(){returnthis.x;}

    public T getY(){returnthis.y;}

}

 

publicclass hello{

    publicstaticvoid main(String args[]){

        //在使用时才确定数据类型为Integer

        Point<Integer> p1 =new Point<Integer>(222,333);

        System.out.println("point_1,x: "+ p1.getX()+", y= "+ p1.getY());

        //在使用时才确定数据类型为String

        Point<String> p2 =new Point<String>("north 38C","east 59C");

        System.out.println("point_2,x: "+ p2.getX()+", y= "+ p2.getY());

    }

}

 

2、  泛型包括泛型类、泛型接口、泛型方法,使用都类似

 

因篇幅问题不能全部显示,请点此查看更多更全内容