- 泛形的基本术语,以ArrayList<E>为例:<>念着typeof
- ArrayList<E>中的E称为类型参数变量
- ArrayList<Integer>中的Integer称为实际类型参数
- 整个称为ArrayList<E>泛型类型
- 整个ArrayList<Integer>称为参数化的类型ParameterizedType
- 以上是常规泛型的应用,下面我们简单介绍自定义泛型应用
- Java程序中的普通方法、构造方法和静态方法中都可以使用泛型。方法使用泛形前,必须对泛形进行声明,语法:<T> ,T可以是任意字母,但通常必须要大写。<T>通常需放在方法的返回值声明之前。例如:
public static <T> void doxx(T t);
public class Test<T>{}
- 我们还可以直接再类上加上泛型的使用,但是需要注意的是即使我们再累上加上泛型,在静态方法上也要加上泛型其它方法可不加。
- 还要注意泛型<T>是引用数据类型(也就是说八种基本类型除外 byte short int long float double char
boolean )
- 下面简单实现以下数组的交换和倒序,和换值
/** 实现一个简单的数组位置的交换 */
public static <T> void test1(T arr[], int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/* 实现数组的倒序 */
public static <T> void test2(T arr[]) {
int startindex = 0;
int endindex = arr.length - 1;
for (;;) {
if (startindex >= endindex) {
break;
}
T temp = arr[startindex];
arr[startindex] = arr[endindex];
arr[endindex] = temp;
startindex++;
endindex--;
}
}
那么我们在main方法中应该怎么调用呢,特别注意必须是应用数据类型
public static void main(String[] args) {
Integer arr[] = { 1, 2, 3, 4 };
// test1(arr,0,2);? 怎么使用呢?引用数据类型
test2(arr);
for (int ar : arr) {
System.out.print("[" + ar + "," + "]");
}
}
只定义两个变量换值
public static void testChange() {
int i = 10;
int j = 111;
// i=11 j=10;
/*
* i=i+j; j=i-j; i=i-j;
*
* System.out.println(i+" "+j);
*/
/*
* 1001 i 1100 j ------- 0101 i 1100 j ----- 1001 j 0101 i 1100 i
*
*
*
* 0101 i 1001 i ------- 1100 j
*/
i = i ^ j; // i
j = i ^ j; // j
i = i ^ j;
System.out.println(i + " " + j);
}