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