- 泛型
泛型在集合中大量被使用,我们可以看到我们经常定义的列表和set
List<String> a = new ArrayList<>();
这就使用了泛型
泛型的定义格式
修饰符 class 类名<代表泛型的变量> { }
class ArrayList<E>{
public boolean add(E e){ }
public E get(int index){ }
....
}
修饰符 <代表泛型的变量> 返回值类型 方法名(参数){ }
public class MyGenericMethod {
public <MVP> void show(MVP mvp) {
System.out.println(mvp.getClass());
}
public <MVP> MVP show2(MVP mvp) {
return mvp;
}
}
修饰符 interface接口名<代表泛型的变量> { }
public interface MyGenericInterface<E>{
public abstract void add(E e);
public abstract E getE();
}
public class MyImp1 implements MyGenericInterface<String> {
@Override
public void add(String e) {
// 省略...
}
@Override
public String getE() {
return null;
}
}
- Iterator迭代器
public class IteratorDemo {
public static void main(String[] args) {
// 使用多态方式 创建对象
Collection<String> coll = new ArrayList<String>();
// 添加元素到集合
coll.add("串串星人");
coll.add("吐槽星人");
coll.add("汪星人");
//遍历
//使用迭代器 遍历 每个集合对象都有自己的迭代器
Iterator<String> it = coll.iterator();
// 泛型指的是 迭代出 元素的数据类型
while(it.hasNext()){ //判断是否有迭代元素
String s = it.next();//获取迭代出的元素
System.out.println(s);
}
}
}
加强for循环的本质是迭代器