泛型初步
假设我们要实现一个功能:实现对数组元素的逆序操作。
功能需求中没有确定数组元素的具体类型,假设我们把类型限定在八大基本类型中。应该如何实现?
- 可以用 “重载方法” 的手段
public static int[] revArray(int[] m) {}
public static long[] revArray(int[] m) {}
这种方法过于笨,为了简化问题的处理,java提供了泛型的概念。
- 泛型解决
public class AboutGeneric {
public static <T> T[] revArray(T[] m) {
T t;
for (int i=0; i<m.length/2; i++) {
t = m[i];
m[i] = m[m.length-1-i];
m[m.length-1-i] = t;
}
return m;
}
}
.
- 泛型标志说明这个方法用到泛型。
- 泛型(T)只能是类类型,所以T就代表某种类类型。
- 编码时不确定,运行时才确定
public class Test {
public static void main(String[] args) {
AboutGeneric Generic = new AboutGeneric();
Integer[] IntegerArray = {1,2,3,4,5,6,7};
// 这里必须写成Integer而不能是int;
for (int num : IntegerArray) {
System.out.print(num);
}
System.out.println();
for (int num : Generic.revArray(IntegerArray)) {
System.out.print(num);
}
}
定义泛型类
public class MyGeneric <T> {
private T number;
public MyGeneric() {
}
public MyGeneric(T number) {
this.number = number;
}
public T getNumber() {
return number;
}
public void setNumber(T number) {
this.number = number;
}
}
类名称后面的 < T > 是“泛型标志”,在此后的代码将T作为类类型。其具体情况在运行时决定。
泛型也可以是多个:
public class MyGeneric <T, K> {
private T number;
public K object;
}