Java -- 增强for循环(foreach)

2023-05-20,,

增强for循环

相对于经典for循环, foreach可以减少代码量,但不是所有情况下foreach都可以代替for循环

当需要修改元素的值或和下标相关的操作需要使用标准for循环

foreach格式

for (数组元素类型 临时变量: 遍历的对象) {}

临时变量代表的是数组的元素,而非下标

foreach对对象进行只读访问, 具有一定的安全性, 因此对数组/集合遍历时优选增强for循环

// 经典for循环
import java.util.Random; int[] arr = new int[5];
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100) + 1;
}
for (int i = 0; i < arr.length; i++) {
int tem = arr[i];
tmp *= 10;
System.out.print(tmp + " ");
}
System.out.println();

以上代码可简化为:

int[] arr = new int[5];
Random r = new Random;
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100) + 1;
}
for (int i: arr2) {
System.out.print((i *= 10) + " ");
}

找出数组中的最值并求和

int max, min, sum;
max = 0x80000000;
min = 0x7FFFFFFF;
sum = 0;
for (int i: arr) {
max = max > i? max: i;
min = min < i? min: i;
sum += i;
}
System.out.println("max: " + max + " min: " + min + " sum: " + sum);

删除列表中指定下标的元素, 并缩减数组

// Person.java
public class Person {
private String name;
private int age; public Person() {
} public Person(String name, int age) {
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String say(Person person) {
return person.name + " " + person.age;
}
}
// Student.java
public class Student extends Person{
private String sno; public Student() {} public Student(String sno) {
this.sno = sno;
} public Student(String sno, String name, int age) {
super(name, age);
this.sno = sno;
} public String getSno() {
return sno;
} public void setSno(String sno) {
this.sno = sno;
} public void say() {
String str = super.say(this);
System.out.println(this.sno + " " + str);
}
}
// Demo.java
Student[] studentArr = new Student[5];
studentArr[0] = new Student("001", "小一", 17);
studentArr[1] = new Student("002", "大二", 18);
studentArr[2] = new Student("003", "张三", 19);
studentArr[3] = new Student("004", "李四", 17);
studentArr[4] = new Student("005", "王五", 18);
int index = 2;
int count = studentArr.length - 1;
// 将删除元素的右侧所有元素左移
for (int i = index; i < studentArr.length - 1; i++) {
studentArr[i] = studentArr[i + 1];
}
// 最后一个元素置为null
studentArr[studentArr.length - 1] = null;
// 调用student的say方法
for (Student student: studentArr) {
if (student != null){
student.say();
} else {
System.out.println(student);
}
}
System.out.println("====================="); // 缩减数组
Student[] studentArray = new Student[count];
for (int i = 0; i < studentArray.length; i++) {
studentArray[i] = studentArr[i];
} // 将旧数组指向新数组地址
studentArr = studentArray; for (Student student: studentArr) {
student.say();
}

Java -- 增强for循环(foreach)的相关教程结束。

《Java -- 增强for循环(foreach).doc》

下载本文的Word格式文档,以方便收藏与打印。