泛型概述
是一种把明确类型的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型。
格式:
<数据类型>
注意:该数据类型只能是引用类型。
好处:避免了强制类型转换,比如上个实验 String s=(String)e.nextElement();
如果我们使用了泛型在抽象的接口中,Interator <String>i=new Collection().interator() ,后面它就会自动认为Interator的对象只能是String ,方便且避免了很多错误。格式 ArrayList<String> a=new ArrayList<String>(); 这是泛型类的使用,泛星还运用在方法上,比如,再函数重载中我们会遇到很多的参数类型,我们就必须要在函数中定义很多的类型,比如:
Class Tool{
piublic void show(String s){
System.out.println(s);
}
piublic void show(int t){
System.out.println(t);
}
}
在主函数中
Tool t=new Tool();
t.show(hello);
t.show(5);
如果参数的类型多的话,就需要重载很多,很麻烦,泛型方法就帮助我们解决了这个问题。
Class Tool{
piublic<T> void show(T s){
c
}
Tool t=new Tool();
t.show(hello);
t.show(5);
此时当输入hello时,自动传递类型String。
然后是泛型接口
我们定义public interface inf<T>{
public abstract void show(T t);
}
实现接口
public Class infimpl<T> implements inf<T>{
public void show(T t){
System.out.println(t);
}
}
增强for
for(元素的数据类型 变量名 : 数组或者Collection集合的对象) {
使用该变量即可,该变量其实就是数组或者集合中的元素。
}
简化了数组和集合的遍历
举例:
ArrayList a=new ArrayList();
a.add("hello");
a.add("boy");
for(String s : a){
System.out.println(s);
}//以前要用迭代器
浙公网安备 33010602011771号