增强for循环的使用
程序员文章站
2024-03-25 16:45:40
...
增强for循环:
JDK5的新特性:自动拆装箱,泛型,增强for,静态导入,可变参数,枚举
(1)增强for 是for循环的一种,增强for其实是用来替代迭代器的
(2)格式:
for(元素的数据类型 变量名 : 数组或者Collection集合的对象) {
使用该变量即可,该变量其实就是数组或者集合中的元素。
}
(3)好处:
简化了数组和集合的遍历
(4)弊端
增强for循环的目标不能为null。建议在使用前,先判断是否为null。
import java.util.ArrayList;
import java.util.Iterator;
/*
* 需求:ArrayList存储自定义对象并遍历。要求加入泛型,并用增强for遍历。
* A:迭代器
* B:普通for
* C:增强for
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// 创建集合对象
ArrayList<Student> array = new ArrayList<Student>();
// 创建学生对象
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("貂蝉", 22);
Student s3 = new Student("杨玉环", 24);
// 把学生对象添加到集合中
array.add(s1);
array.add(s2);
array.add(s3);
// 迭代器
Iterator<Student> it = array.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.getName() + "---" + s.getAge());
}
System.out.println("---------------");
// 普通for
for (int x = 0; x < array.size(); x++) {
Student s = array.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
System.out.println("---------------");
// 增强for
for (Student s : array) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
上一篇: RESTful