初识java泛型

泛型是JAVA SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。这种参数类型可以用在类、接口和方法的创建中,分别称为泛型类、泛型接口、泛型方法。

JAVA语言引入泛型要解决的问题是 实现参数的 任意化 , 好处是安全简单。

在JAVA SE 1.5之前,没有泛型的情况的下,通过对类型Object的引用来实现参数的“任意化”,“任意化”带来的缺点是要做显式的强制类型转换,而这种转换是要求开发者对实际参数类型可以预知的情况下进行的。对于强制类型转换错误的情况,编译器可能不提示错误,在运行的时候才出现异常,这是一个安全隐患。

泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。

泛型在使用中还有一些规则和限制:
1、泛型的类型参数只能是类类型(包括自定义类),不能是简单类型。
2、同一种泛型可以对应多个版本(因为参数类型是不确定的),不同版本的泛型类实例是不兼容的。
3、泛型的类型参数可以有多个。
4、泛型的参数类型可以使用extends语句,例如。习惯上成为“有界类型”。
5、泛型的参数类型还可以是通配符类型。例如Class classType = Class.forName(java.lang.String);

例如,

 java |  copy code |? 
01
02
package generic;
03
 
04
public class Gen<T> {
05
	private T t; // 定义泛型成员变量
06
 
07
	public Gen(T t) {
08
		this.t = t;
09
	}
10
 
11
	public T getT() {
12
		return t;
13
	}
14
 
15
	public void setT(T t) {
16
		this.t = t;
17
	}
18
 
19
	public void showType() {
20
		System.out.println(" T的实际类型是= " + t.getClass().getName());
21
	}
22
}
23

 java |  copy code |? 
01
02
package generic;
03
 
04
public class genTest {
05
 
06
	public static void main(String args[]) {
07
		Gen<Integer> intOb = new Gen<Integer>(88);
08
		intOb.showType();
09
		int i = intOb.getT();
10
		System.out.println("value= " + i);
11
 
12
 
13
		Gen<String> st = new Gen<String>("this is a String");
14
		st.showType();
15
		String j = st.getT();
16
		System.out.println("value= " + j);
17
 
18
	}
19
}
20
 
21

Posted in java学习 | Tags:

0 Comments.

Leave a Reply

[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Get Adobe Flash playerPlugin by wpburn.com wordpress themes