泛型简单认识

来源:互联网 发布:c语言的创始人 编辑:程序博客网 时间:2024/06/05 16:50
自定义范型声明的位置:
public <T> T a(T t)
{
}
也可以直接在类上进行声明。public calss Demo6<T,E,K>
当使用静态方法是,类中的声明有的情况下,依然需要在方法中单独声明。
publlic static <T> void c(T t)
public class StringFoo {
private String x;
public StringFoo(String x) {
this.x = x;
}
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
}
public class DoubleFoo {
private Double x;
public DoubleFoo(Double x) {
this.x = x;
}
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
}
这个类对上面两个类进行了重构。
public class ObjectFoo {
private Object x;
public ObjectFoo(Object x) {
this.x = x;
}
public Object getX() {
return x;
}
public void setX(Object x) {
this.x = x;
}
}
这里是上面的demo方法
写出Demo方法如下:
public class ObjectFooDemo {
public static void main(String args[]) {
ObjectFoo strFoo = new ObjectFoo(new StringFoo("Hello Generics!"));
ObjectFoo douFoo = new ObjectFoo(new DoubleFoo(Double("33")));//生成的类的对象需要提前知道,进行强转。
ObjectFoo objFoo = new ObjectFoo(new Object());
System.out.println("strFoo.getX="+(StringFoo)strFoo.getX());
System.out.println("douFoo.getX="+(DoubleFoo)douFoo.getX());
System.out.println("objFoo.getX="+objFoo.getX());
}
}
使用泛型之后的效果。
public class GenericsFoo<T> {
private T x;
public GenericsFoo(T x) {
this.x = x;
}
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
}
public class GenericsFooDemo {
public static void main(String args[]){
GenericsFoo<String> strFoo=new GenericsFoo<String>("Hello Generics!");//使用泛型之后这里进行了多态,不再需要知道具体
GenericsFoo<Double> douFoo=new GenericsFoo<Double>(new Double("33"));//生成类的类型,不要在强转的时候需要对应。
GenericsFoo<Object> objFoo=new GenericsFoo<Object>(new Object());
System.out.println("strFoo.getX="+strFoo.getX());
System.out.println("douFoo.getX="+douFoo.getX());
System.out.println("objFoo.getX="+objFoo.getX());
}
}
泛型,通过多态的思想,使我们不需要知道需要生成的对象时什么类型的,简化了代码的编辑。
范型的相关介绍:
ArrayList<E>
ArrayList<E>中的E成为类型参数变量
ArrayList<Integer>中的integer称为实际类型参数
整个称为ArrayList<E>范型参数
整个ArrayList<Integer>称为参数化的类型
0 0