泛型是Java 5 的新特性,其本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。这种数据类型的指定可以使用在类、接口和方法的创建中,分别称为泛型类、泛型方法和泛型接口。具体定义如下:
- 泛型类的定义是在类名后面加上“<Type>”,例如:
class A <Type> {
}
class B <Type1,Type2>{
- 泛型方法的定义是在方法前加上“<Type>”,例如:
class A{
<Type> void fun1(){
}
<Type1,Type2> void fun2(){
}
- 泛型接口的定义是在接口名称后面加上 <Type>,跟泛型类定义相似
泛型起因:
- JAVA5使用泛型以前类型不明确:
- 装入集合的类型都被当做Object对待,从而失去自己的实际类型。
- 从集合中取出时往往需要强制类型转换,效率低,容易产生错误。
例如:我们将一只狗扔进一个Map集合里,这时它继承了父类的类型,变成Object 类型。从而丢失了自身的类型。当我们需要取出的时候,就需要强制类型转换,但是如果我们将狗不小心强制转换成猫类型,这时候就会产生错误。
而对于强制类型转换的错误,在程序编译期间,不会提示错误,只有在运行时才会出现异常,从而在代码中存在安全隐患。
在Java 5 之前,为了让类具有通用型,往往将类的属性、函数的参数类型,函数的返回值都设置为Object。当要获取函数的返回值并使用时,必须将其返回值强制转换为原类型或接口,然后才可以调用原类型的方法。
未使用泛型实例:
import java.util.*;
public class TestMap{
public static void main(String args[]){
Map m1 = new HashMap();
Map m2 = new TreeMap();
m1.put("one",new Integer(1)); //转换参数为Integer类型
m1.put("two",new Integer(2));
m1.put("three",new Integer(3));
m2.put("A",new Integer(1));
m2.put("B",new Integer(2));
if (m1.containsKey("two")){
int i = ((Integer)m1.get("two")).intValue(); //强制转换为Integer类型
System.out.println(i);
}
Map m3 = new HashMap(m1);
m2.putAll(m2);
System.out.println(m3);
}
}
上述代码虽然可以通过编译,但是在运行时却会出现以下异常:
使用泛型的实例:
public class test{
public static void main(String[] args){
GeneralType<Integer>a = new GeneralType<Integer>(2);
GeneralType<Double>b = new GeneralType<Double>(0.55);
System.out.println("a.object=" + a.getObj());
//System.out.println("a.object="+(Integer)b.getObj()); //不能通过编译
}
}
class GeneralType<Type> {
Type object;
public GeneralType (Type object){
this.object = object;
}
public Type getObj(){
return object;
}
}
泛型的使用,还涉及到通配符泛型和有限制的泛型。
通配符泛型用<?>表示,"?"表示任意一种泛型。例如:
public class test{
public static void main(String[] args){
ShowType st = new ShowType();
GeneralType<Integer>i = new GeneralType<Integer>(2);
GeneralType<String>s =new GeneralType<String>("hello");
st.showType(i);
st.showType(s);
}
}
class GeneralType<Type> {
Type object;
public GeneralType (Type object){
this.object = object;
}
public Type getObj(){
return object;
}
}
class ShowType{
public void showType(GeneralType<?>o){
System.out.println(o.getObj().getClass().getName());
}
}
有时候需要将泛型中参数代表的类型做限制,此时可以使用有限制的泛型。有限制泛型是指在参数 “Type” 后面使用"extends"关键字并加上类名或接口名,表明参数所代表的类型必须是该类型的关键字或者实现了该接口。 例如:
public class test{
public static void main(String[] args){
GeneralType<Integer>i = new GeneralType<Integer>(2);
}
}
//限制参数类型只能是Number或者Number的子类
class GeneralType<Type extends Number> {
Type object;
public GeneralType (Type object){
this.object = object;
}
public Type getObj(){
return object;
}
}
上面是几种泛型的使用,由此可见使用泛型不会对值进行强制转换,增加了程序的灵活性,同时可以避免因为强制类型转换而带来的问题,使代码变得更加简答、安全。特别是在使用集合时,我们尽量使用泛型来增强程序的可读性和稳定性。