JAVA基础之泛型应用
泛型:JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。
好处
1、将运行时期出现问题ClassCastException,转移到了编译时期,方便于程序员解决问题。让运行时问题减少,安全!
2、避免了强制转换麻烦。
通常在集合框架中很常见,
只要见到<>就要定义泛型。
其实<> 就是用来接收类型的。
当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。
泛型定义在集合中
<span style="font-size:18px;"> public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();//通过<>来定义要操作的引用数据类型。
al.add("abc01");
al.add("abc0991");
al.add("abc014");
Iterator<String> it = al.iterator();
while(it.hasNext())
{
String s = it.next();
System.out.println(s+":"+s.length());
}
}</span>
泛型定义在接口上
<span style="font-size:18px;">interface Inter<T>
{
void show(T t);
}
class InterImpl<T> implements Inter<T>
{
public void show(T t)
{
System.out.println("show :"+t);
}
}
class GenericDemo
{
public static void main(String[] args)
{
InterImpl<Integer> i = new InterImpl<Integer>();
i.show(4);
}
}</span>
泛型定义在类上
<span style="font-size:18px;">class DemoT<T>
{
public void show(T t)
{
System.out.println("show:"+t);
}
public <Q> void print(Q q)
{
System.out.println("print:"+q);
}
public static <W> void method(W t)
{
System.out.println("method:"+t);
}
}
class GenericDemo
{
public static void main(String[] args)
{
DemoT <String> d = new DemoT<String>();
d.show("haha");
d.print(5);
d.print("hehe");
DemoT.method("hahahahha");
}
}</span>