Iterator迭代器遍历的两种方式:while和for
while方式
Iterator it = 集合对象.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
for方式
for (Iterator it = 集合对象.iterator(); it.hasNext();) {
System.out.println(it.next());
}
建议使用for循环方式
因为 for循环中的迭代器对象it是在循环里面,循环结束后it的生命周期也会结束!
而while循环方式迭代器对象在while循环体的外面,会在内存中占用一定的资源!不推荐使用!