`
Longmanfei
  • 浏览: 46511 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

泛型的"另类"应用

J# 
阅读更多

 

  • 泛形的基本术语,以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 )

 

  • 下面简单实现以下数组的交换和倒序,和换值
/** 实现一个简单的数组位置的交换 */
	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);

	}
 

 

 

分享到:
评论
8 楼 moqinan 2011-03-08  
受教啊!其实大家么必要那么深究。。。
7 楼 Longmanfei 2011-03-02  
bingoohuang 写道
又是“标题党”

首先另类我加了引号希望不要误解,其次大概是层次级别比较高,所以觉得贴比较菜 哈哈
6 楼 bingoohuang 2011-03-02  
又是“标题党”
5 楼 songlixiao 2011-03-02  
没看出另类在哪呀?
4 楼 jefery_liang 2011-03-01  
泛型很不错啊,值得学习
3 楼 7454103 2011-03-01  
喜欢泛型!
很不错的帖子! (还可以再 深究下! 泛型参数 ,泛型方法,extend super ? 等! )
2 楼 Longmanfei 2011-03-01  
又学习了
1 楼 Unmi 2011-03-01  
java 的泛型还有更有意思的用法,比如声明这样的方法:
public static <T,U> T getByIdx(T[] a, U b){

调用时的代码为:
String name = ArrayAlg.<String, Date>getByIdx(names,new Date());

或者隐式的:
String name1 = ArrayAlg.getByIdx(names,"GameOver");

有时必须显式的指明参数类型

我原来也整理过三篇《步步理解 JAVA 泛型编程》系列,还有诸如 extends, ? 等形式:
1. http://unmi.cc/understand-java-generic-1
2. http://unmi.cc/understand-java-generic-2
3. http://unmi.cc/understand-java-generic-3

相关推荐

Global site tag (gtag.js) - Google Analytics