好处:
1、将运行时出现的问题 ClassCastException,转移到了编译时期、提前确定类型,保证安全问题。
2、避免了强制转换
泛型格式: 通过<>来定义操作引用的数据类型。
在使用JAVA提供的对象时,什么时候写泛型呢
class Demo { public <T> void show(T t) { System.out.println("show:"+t); } public <T> void print(T t) { System.out.println("print:"+t); } public <Q> void method(Q q) { System.out.println("method:"+q); } /*泛型类的定义、可以定义在类上,也可以定义在方法上。*/ } class Demo2<T> { public void show(T t) { System.out.println("show:"+t); } public void print(T t) { System.out.println("print:"+t); } public <Q> void method(Q q) { System.out.println("method:"+q); } }
接口
interface Inter<T>
{
void show(T t);
}
/*
class InterImpl implements Inter<String>
{
public void show(String t)
{
System.out.println("show:"+t);
}
}
*/
class InterImpl<T> implements Inter<T>
{
public void show(T t)
{
System.out.println("show:"+t);
}
}
? 通常在集合框架中很常见,只要见到<>就定义泛型
当使用集合时候,将集合中要存储的数据类型作为参数传递到<>当中即可
泛型类: 什么时候需要泛型类
当类中要操作的引用数据类型不确定的时候,早期定义Object来完成拓展、现在定义泛型
避免了强转、将错误转移到了编译时期。
/*特殊之处: 静态方法不可以访问类上定义的泛型。 如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上*/