迭代器
格式:
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
System.out.println(next);
package com.bignyi;
import com.domain.Student;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest1 {
public static void main(String[] args) {
method();
}
private static void method() {
Collection<String> c = new ArrayList<>();
c.add("2342");
c.add("2342");
c.add("2342");
c.add("2342");
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
System.out.println(next);
}
}
}
增强for循环
简化迭代器的书写
格式:
for(元素的数据类型 变量名:数组或者集合){
}
public static void main(String[] args) {
Collection<Student> c = new ArrayList<>();
c.add(new Student("张三",33));
c.add(new Student("张四",34));
for (Student student : c) {
System.out.println(c);
}
}
foreach方法
public static void main(String[] args) {
Collection<Student> c = new ArrayList<>();
c.add(new Student("张三",33));
c.add(new Student("张四",34));
c.forEach(student -> System.out.println(student));
}
格式:c.forEach(元素的数据类型-> System.out.println(student));