Java 范型

2018-09-25  本文已影响0人  Jack_6a46

范型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。
范型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。
使用Java范型的概念,我们可以写一个范型方法对一个对象数组排序,然后,调用该范型方法来对整形数组、浮点型数组、字符串数组等进行排序。

范型方法

可以写一个范型方法,该方法在调用时可以接收不同类型的参数。根据传递给范型方法的参数类型,编译器适当地处理每一个方法调用。

下面是定义范型方法的规则:

·所有范型方法声明都有一个类型参数声明部分(由尖括号分隔),该类型参数声明部分在方法返回类型之前。
·每一个类型参数声明部分包含一个或多个类型参数,参数间用逗号隔开。
·类型参数能被用来声明返回值类型,并且能作为范型方法得到的实际参数类型的占位符。
·范型方法体的声明和其他类型一样。
例子:

  public class Main {
  public static <E> void printArray(E[] inputArray){
    for(E element : inputArray){
        System.out.print(element + " ");
    }
    System.out.println();
}
public static void main(String[] args) {
// write your code here
    Integer[] intArray = {1, 2, 3, 4, 5};
    Double[] doubleArray = {1.2, 1.3, 1.5, 88.99};
    Character[] charArray = {'J', 'a', 'c', 'k'};
    printArray(intArray);
    printArray(doubleArray);
    printArray(charArray);
}

}

下面的例子演示了"extends"如何使用在一般意义上的意思。该例子中的范型方法返回三个可比较对象的最大值。

public class Main {
public static <T extends Comparable<T>> T maximum(T x, T y, T z){
    T max = x;
    if(y.compareTo(max) > 0){
        max = y;
    }
    if(z.compareTo(max) > 0){
        max = z;
    }
    return max;
}
public static void main(String[] args) {
// write your code here
    System.out.printf("%d, %d, %d中的最大的数为 %d\n", 3 , 4, 5, maximum(3, 4, 5));

    System.out.printf("%.1f, %.1f, %.1f中最大的数为 %.1f\n", 3.3, 4.5, 8.8, maximum(3.3, 4.5, 8.8));

    System.out.printf("%s, %s, %s中最大的数为 %s\n", "jack", "madge",
            "sammy", maximum("jack","madge", "sammy"));
  }
  }

泛型类

泛型类的声明和非泛型类的声明类似,除了在类名后面添加了类型参数声明部分。
和范型方法一样,泛型类的类型参数声明部分也包含一个或多个类型参数,参数间用逗号隔开。一个范型参数,也被称为一个类型变量,是用于指定一个范型类型名称的标识符。因为它们接受一个或多个参数,这些类被称为参数化的类或参数化的类型。

public class Box<T> {
private T t;
public void add(T t){
    this.t = t;
}

public T get(){
    return t;
}
}

public class Main {
public static void main(String[] args) {
// write your code here
    Box<Integer> integerBox = new Box<Integer>();
    Box<String> stringBox = new Box<String>();

    integerBox.add(new Integer(100));
    stringBox.add(new String("jj"));

    System.out.printf("整形值为: %d\n", integerBox.get());
    System.out.printf("字符串为: %s", stringBox.get());
}
}

类型通配符

  1. 类型通配符一般使用?代替具体的参数类型。例如List<?> 在逻辑上是 List<String>, List<Integer>等所有 List<具体类型参数>的父类。
    实例:
public class Main {
public static void main(String[] args) {
    List<String> name = new ArrayList<String>();
    List<Integer> age = new ArrayList<Integer>();
    List<Number> number = new ArrayList<Number>();
    name.add("Jack");
    age.add(22);
    number.add(108);
    getData(name);
    getData(age);
    getData(number);
}
public static void getData(List<?> data){
    System.out.println("Data: " + data.get(0));
}
}
上一篇下一篇

猜你喜欢

热点阅读