泛型Generic

作者: BL觉醒 | 来源:发表于2017-09-27 10:53 被阅读0次

    用二位坐标定义一个平面上的点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);
        }     
    }
    

    相关文章

      网友评论

        本文标题:泛型Generic

        本文链接:https://www.haomeiwen.com/subject/tgmyextx.html