Java -- 增强for循环(foreach)
增强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)的更多相关文章
- “全栈2019”Java第三十二章:增强for循环Foreach语法
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- Java 增强 for 循环
Java 增强 for 循环 Java5 引入了一种主要用于数组的增强型 for 循环. Java 增强 for 循环语法格式如下: for(声明语句 : 表达式) { //代码句子 } 声明语句:声 ...
- java增强for循环中获取index
java增强for循环中获取index http://rensanning.iteye.com/blog/2003205
- java 增强for循环与泛型
一 增强for循环 增强for循环是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的.它的内部 原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作 ...
- Java中的增强 for 循环 foreach
foreach 是 Java 中的一种语法糖,几乎每一种语言都有一些这样的语法糖来方便程序员进行开发,编译期间以特定的字节码或特定的方式来对这些语法进行处理.能够提高性能,并减少代码出错的几率.在 J ...
- java 流程执行 循环 foreach循环
一. if分支 1. 结构 if else if else 2.执行原则 if if if 结构 会一直去执行()里的判断语句 if else if else if 结构 只要一条( ...
- 增强for循环 -- foreach循环
1 作用 简化迭代器的书写格式.(注意:foreach循环的底层还是使用了迭代器遍历.) 2 适用范围 如果是实现了Iterable接口的对象或者是数组对象都可以使用foreach循环. 3 格 ...
- JAVA增强for循环
作用:简化数组和集合的遍历 格式:for(元素数据类型 变量 :数组或者集合) 例子: Map map=new HashMap; for(Object obj :map.keySet()){ Obj ...
- java 增强for循环对于空集和null的判断
List<String> list = null; for (String str : list) {//会报空指针异常 System.out.println(str); } List&l ...
- Java基础系列(24)- 增强for循环
增强for循环 这里我们先只是见一面,做个了解,之后数组部分会重点使用 Java5引入了一种主要用于数组或集合的增强型for循环 Java增强for循环语法格式如下 for(声明语句:表达式){ // ...
随机推荐
- Java基础Day6-面向对象
一.面向对象编程(Object-Oriented Programming, OOP) 面向对象编程的本质就是:以类的方式组织代码,以对象的组织(封装)数据. 从认识论的角度:先有对象后有类.对象是具体 ...
- unable to access 'http://*****/': The requested URL returned error: 414
git拉取gitlab项目: unable to access 'http://git.yijiago.com/meimeng/lsyjg_java.git/': The requested URL ...
- springboot启动图标banner
将springboot项目中的banner.txt文件替换成下面代码即可 ${AnsiColor.BRIGHT_YELLOW} ┏━┓ ┏━┓ ┏┛ ┻━━━━━┛ ┻┓ ┃ ┃ ┃ ━ ┃ ┃ ┳┛ ...
- 微信小程序——石头剪刀布
博客班级 https://edu.cnblogs.com/campus/zjcsxy/SE2020 作业要求 https://edu.cnblogs.com/campus/zjcsxy/SE2020/ ...
- 【Unity】Timeline探索记(4)第二个例子——动作特写/子弹时间
写在前面 这次例子参考这篇实现博文(附带项目下载),博文前面介绍非常具体,可惜后面特写轨实现代码不是按照我想要的标准四大件(data.mixer.clip.track)来组织的,所以这里我略过介绍,只 ...
- python 连接蓝牙设备并接收数据
python 连接蓝牙设备 原始内容 # %% from binascii import hexlify import struct from bluepy.btle import Scanner, ...
- Field userService in com.lin.hms.controller.LogController required a bean of type 'org.lin.hms.service.UserService' that could not be found.
需要一个bean但找不到 解决 我们在controller使用的service没有注入spring容器,那么我们可以在启动类上,加上包扫描注解,让这个bean所在的包能扫描到: @ComponentS ...
- 创建function函数sys_guid时报错
创建function函数sys_guid时报错 执行下面的命令 show variables like 'log_bin_trust_function_creators';set global log ...
- Codeforces Round #803 (Div. 2) A-D 刚vp完还没补题
Codeforces Round #803 (Div. 2) 2022/7/24 上午VP 传送门:https://codeforces.com/contest/1698 A. XOR Mixup 随 ...
- mysql数据库用sql语句在指定的一个字段后面添加一个字段
alert table (新增列的表名) add (新列名) comment (添加备注)+[after + 要跟随的字段名]可写可不写 ALTER TABLE ch_poliy_info AD ...