没有泛型的情况
数据类型转换比较复杂
String i2=(String)g1.getObj(); //不能确定转换过程中g1原来的类型
Integer i3=(Integr)g2.getObj();
在转换过程中会产生不安全因素
泛型就是将类型参数化,提高类型的安全并简化类型的转换过程。
安全:泛型就是将类型的错误提前到编译期,普通强制转换只是在运行期才能发现错误
泛型处理的是类的类型不是int,long的类型,例如Gen<int>g1 =new Gen<int>(i1)是错误的
测试程序:
package fanxing;
public class Gen<T>//将类型参数化
{
Tobj;
Gen(Tobj)
{
this.obj =obj;
}
public T getObj()
{
return obj;
}
public void showType()
{
System.out.println("对象的类型是:" +obj.getClass().getName());
}
}
package fanxing;
public class testGen
{
public static void main(String[]args)
{
//TODO Auto-generated method stub
Integeri1 =new Integer(10);
Strings1 =new String("hello world!");
Gen<Integer>g1 =new Gen<Integer>(i1);
Integeri2 =g1.getObj();//不再需要强制转换 自动完成类型的转换
System.out.println(i2);
g1.showType();
Gen<String>g2 =new Gen<String>(s1);
Strings2=g2.getObj();
System.out.println(s2);
g2.showType();
}
}
多个泛型参数
package fanxing2;
public class TwoGen<T, V> // 两个类型参数
{
T obj1;
V obj2;
public TwoGen(T t, V v)
{
this.obj1 = t;
this.obj2 = v;
}
public T getObj1()
{
return obj1;
}
public V getObj2()
{
return obj2;
}
public void showType_t()
{
System.out.println("对象obj1的类型是:" + obj1.getClass().getName());
}
public void showType_v()
{
System.out.println("对象obj2的类型是:" + obj2.getClass().getName());
}
}
package fanxing2;
import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode;
public class TestTwoGen
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Integer i1 = new Integer(11);
Integer i2 = new Integer(22);
String s1 = new String("s1");
String s2 = new String("s2");
//声明第一个泛型对象<Integer,integer>
TwoGen<Integer, Integer> g1 =
new TwoGen<Integer, Integer>(i1, i2);
g1.showType_t();
g1.showType_v();
System.out.println("g1.obj1的内容:"+g1.getObj1());
System.out.println("g1.obj2的内容:"+g1.getObj2());
//声明第二个泛型对象<String,String>
TwoGen<String, String> g2 =
new TwoGen<String, String>(s1, s2);
g2.showType_t();
g2.showType_v();
System.out.println("g2.obj1的内容:"+g2.getObj1());
System.out.println("g2.obj2的内容:"+g2.getObj2());
}
}