泛型


概述

  1、泛型是在JDK1.5之后增加的新功能,泛型(Generic)
  2、泛型可以解决数据类型的安全性问题,原理:在类声明的时候通过一个标识表示类中某个属性的类型或者某个方法的返回值及参数类型
  3、格式:

  访问权限 class 类名称<泛型, 泛型, ...> {
    属性
    方法
  }

  4、对象的创建
      类名称<具体类型> 对象类型 = new 类名称<具体类型>()
  5、多个泛型示例:

public class A<K, T> {
  private K x;
  private T y;
  
  public K getX() {
    return this.x;
  }
  public void setX(K x) {
    this.x = x;
  }
  public T getY() {
    return this.y;
  }
  public void setY(T y) {
    this.y = y;
  }
}

public class Test {
  public static void main(String[] args) {
    A<String, Integer> a = new A<String, Integer>();
    a.setX = "经度为: ";
    a.setY = 109;
    System.out.println(a.getX() + " , " + a.getY());
  }
}

通配符的使用

public class A<K, T> {
  private K x;
  private T y;
  
  public K getX() {
    return this.x;
  }
  public void setX(K x) {
    this.x = x;
  }
  public T getY() {
    return this.y;
  }
  public void setY(T y) {
    this.y = y;
  }
  @Override
  public String toString() {
    return this.getX() + " , " + this.getY();
  }
}

public class Test {
  public static void main(String[] args) {
     // 由于 tell() 方法使用通配符指定的 泛型类型,所以此处可以随意填写具体的泛型类型
    A<String, Integer> a = new A<String, Integer>();
    a.setX = "经度为: ";
    a.setY = 109;
    this.tell(a);
  }
  // 使用通配符 ? 指定泛型类型
  public static void tell(A<?, ?> a) {
    System.out.println(a);
  }
}

泛型接口

  1、在JDK1.5之后,不仅仅可以声明泛型类,也可以声明泛型接口,声明泛型接口和声明泛型类语法类似,在接口名称后面加上<T>
  2、格式:interface 接口名称<泛型标识> {}
  3、示例:

interface GenInter<T> {
  public void say();
}
class Gin<T> implements GenInter<T> {}
public class Test {
  public static void main(String[] args) {
    Gin<String> gin = new Gin<String>();
  }
}

泛型方法

  1、泛型方法中可以定义泛型参数,此时,参数的类型就是传入数据的类型。
  2、格式:<泛型标识> 泛型标识 方法名称([泛型标识 参数名称])
  3、示例

class Gener {
  public <T>T tell(T t) {}
}
public class Test {
  public static void main(String[] args) {
    Gener g = new Gener();
    String str = g.tell("hi, barret ! ");
    System.out.println(str); // Output:hi, barret !
    int i = g.tell(666);
    System.out.println(i); // Output:666
  }
}

泛型数组

  1、泛型数组需要个泛型方法搭配使用,在使用泛型方法的时候,可以传递或返回一个泛型数组
  2、示例

public class Test {
  public static void main(String[] args) {
    String arr[] = {"hi", "barret", "!"};
    this.tell(arr); // Output:hi , barret , ! , 
    Integer arr2[] = {1, 2, 3, 4, 5};
    this.tell(arr); // Output:1 , 2 , 3 , 4 , 5 , 
  }
  public static <T>void tell(T arr[]) {
    for(int i = 0; i <= arr.length; i++) {
      System.out.print(arr[i] + " , ");
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容