一、泛型是在JDK1.5之后增加的新功能。泛型(Generic)
可以避免经常出现的数据类型转换异常
二、泛型可以解决数据类型的安全问题,它主要的原理,是在类声明的时候通过一个标识表示类中某个属性的类型或者是某个方法的返回值及参数类型。
三、格式
访问权限 class 类名称<泛型,泛型...>{
属性
方法
}四、对象的创建
类名称<具体类型> 对象名称 = new 类名称<具体类型>();
五、代码演示
class Point<T>{
private T x;
private T y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return y;
}
public void setY(T y) {
this.y = y;
}
}
public class GenericDemo01 {
public static void main(String[] args) {
Point<String> pS = new Point<String>();
pS.setX("经度为10");
pS.setY("纬度为100");
System.out.println(pS.getX()+" "+pS.getY());
Point<Integer> pI = new Point<Integer>();
pI.setX(10);
pI.setY(100);
System.out.println("经度:"+pI.getX()+" 纬度:"+pI.getY());
Point<Float> pF = new Point<Float>();
pF.setX(10.0f);
pF.setY(100.0f);
System.out.println("经度:"+pF.getX()+" 纬度:"+pF.getY());
}
}执行结果:
经度为10 纬度为100 经度:10 纬度:100 经度:10.0 纬度:100.0
原文:http://11317783.blog.51cto.com/11307783/1763630