泛型:JDK1.5版本以后出现的新特性。用于解决安全问题,是一个类型安全机制。
好处:
1,在运行时期出现问题ClassCastException ,转移到了编译时期。
方便程序员解决问题,让运行时期问题减少,安全。
2,避免了强制转换的麻烦。
3,泛型格式:通过<>来定义要操作的引用数据类型。
在使用java提供的对象时,什么时候写泛型呢?
通常在集合框架中很常见,只要见到<>就要定义泛型。
其实<>就是用来接收类型的
当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。
定义泛型时,放到返回值类型的前面。
import java.util.*;
public class GenericDemo {
public static void main(String[] args){
ArrayList
al=new ArrayList
();
al.add("djehnwif");
al.add("3eefde");
al.add("de3");
al.add("45t645gf");
Iterator
it=al.iterator();
while(it.hasNext()){
String s=it.next();
System.out.println(s+":"+s.length());
}
}
}
djehnwif:8
3eefde:6
de3:3
45t645gf:8
4,泛型类:
class worker{
}
class poet{
}
class utils<QQ>{
private QQ q;
public void setObject(QQ q){
this.q=q;
}
public QQ getObject(){
return q;
}
}
public class GenericDemo2 {
public static void main(String[] args){
utils<worker> u=new utils<worker>();
u.setObject(new worker());
worker w=u.getObject();
}
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">5,当泛型定义在方法上:</span>
class Demo{
public<T> void show(T t){
System.out.println("show:"+t);
}
public<Q> void print(Q q){
System.out.println("print:"+q);
}
}
public class GenericDemo3 {
public static void main(String[] args){
Demo d=new Demo();
d.show("haha");
d.show(new Integer(4));
d.print(6);
d.print("deiuj");
}
}
运行结果:
show:haha
show:4
print:6
print:deiuj
静态方法不可访问类上定义的泛型。例如下面代码就会编译失败
class Demo<T>{
public static void show(T t){
System.out.println("show:"+t);
}
}
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上,例如:
class Demo<T>{
public static<span style="color:#ff0000;"><W></span> void show(W w){
System.out.println("show:"+w);
}
}
7 泛型定义在接口上,代码如下:
interface inter<T>{
void show(T t);
}
class InterImp implements inter<String>{
public void show(String str){
System.out.println("show:"+str);
}
}
public class GenericDemo4 {
public static void main(String[] args){
InterImp i=new InterImp();
i.show("hahah");
}
}
打印结果:
show:hahah