public class Itertor {
public static void main(String[] args) {
System.out.println("-----List的容器类的迭代器-----");
List<String> ss = new ArrayList<>();
ss.add("a");
ss.add("b");
ss.add("c");
/*
* 获取迭代器对象
* */
Iterator<String> ff = ss.iterator();
//判断当前游标位置是否有元素
boolean g = ff.hasNext();
System.out.println(g);
//如果当前游标有元素,就将此元素给str变量,并且打印变量
if (g) {
String str=ff.next();
System.out.println(str);
}
System.out.println("-------在迭代器中通过while循环通过元素--------");
while (ff.hasNext()) {
System.out.println(ff.next());
}
System.out.println("------在迭代器中通过for循环获取元素------");
//没调用一个元素,创建一个迭代器对象,并将游标后移一位
//迭代器对象只能使用一次
for (Iterator<String> n= ss.iterator();n.hasNext();){
System.out.println(n.next());
}
System.out.println("------set容器类的迭代--------");
System.out.println("------在迭代器中通过while循环获取元素------");
//创建hashset容器对象
Set<String> m = new HashSet<>();
//添加元素
m.add("x");
m.add("y");
m.add("z");
//创建迭代器对象
Iterator<String> k = m.iterator();
//while循环迭代
while (k.hasNext()){
System.out.println(k.hasNext());
}
System.out.println("-------在迭代器中通过for循环获取元素-------");
for (Iterator<String> h=m.iterator();h.hasNext();) {
System.out.println(h.next());
}
}
}
Java学习笔记<十一>(Collection:Itertor)
于 2022-04-15 18:44:15 首次发布