泛型Generic

用二位坐标定义一个平面上的点a(x,y):

public class Point() {
private int x ;//x轴坐标
private int y ;//y轴坐标

public int getX() {
return x ;
}
public int setX(int x) {
this.x = x;
}
public int getY() {
return y ;
}
public int setY(int y) {
this.y = y ;
}
}

精度不够,提高精度需要重新定义高精度的类:

public class DoublePoint() {
private double x ;
private double y ;

public double getX() {
return x ;
}
public double setX(double x) {
this.x = x;
}
public double getY {
return y ;
}
public double setY(double y) {
this.y = y;
}
}

上面定义的两个类的代码非常相似,但无法复用。用泛型可提高代码复用率,减少重复。

public class Point<T>{
private T x ;
private T y ;

public T getX() {
return x ;
}
public T setX(T x) {
this.x = x ;
}
public T getY() {
return y ;
}
public T setY(T y) {
this.y = y ;
}
}

另一个实例,容器类:容器中可以存放各种类型的对象

public class Container<T> {
private T variable ;

public Container () {
variable = null ;
}
public Container(T variable) {
this.variable = variable ;
}
public T get() {
return variable ;
}
public void set(T variable) {
this.variable = variable ;
}
public static void main(String[] args) {
Container<String> stringContainer = new Container<String>() ;
stringContainer.set("This is a string.") ; 
}
}

多个泛型参数:

public class Triple<A, B, C> {
    private A a;
    private B b;
    private C c;

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b = b;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

}
Triple<String, Integer, Float> triple = new Triple<String, Integer, Float>();
triple.setA("something");
triple.setB(1);
triple.setC(1.0f);

泛型方法:泛型也可以直接应用在一个方法中,不要求这个方法所属的类为泛型类。与泛型类不同的是泛型方法需要在方法返回值前用尖括号声明泛型类型名,这样才能在方法中使用这个标记作为返回值类型或参数类型。

public class Printer {
    public static <T> void printArray(T[] objects) {
        if (objects != null) {
            for(T element : objects){  
                System.out.printf("%s",element);  
            }  
        }
    }
    
    public static void main(String[] args) {  
        Integer[] intArray = { 1, 2, 3, 4, 5 };  
        Character[] charArray = { 'T', 'I', 'A', 'N', 'M', 'A', 'Y', 'I', 'N', 'G' };
        
        printArray(intArray);
        printArray(charArray);
    }     
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容