当前位置:网站首页>Half of the people don't know the difference between for and foreach???
Half of the people don't know the difference between for and foreach???
2022-07-07 11:30:00 【Java technology stack】
Click on the official account ,Java dried food Timely delivery 
Recommended reading :Spring Cloud Alibaba Finally unify the Jianghu !
A colleague suddenly asked me a question , Said in foreach Can I delete it list The elements inside , I said about whether I could delete , And why ; Next, let's explore whether this can be done ;
(1) Traversing elements
First , Let's take a piece of code as an example :
String[] array = {"1", "2", "3"};
for (String i : array) {
System.out.println(i);
}
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
for (String i : list) {
System.out.println(i);
}After traversal, the results are as follows :
1
2
3
111
222
333String[] array = new String[]{"1", "2", "3"};
String[] var2 = array;
int var3 = array.length;
for(int var4 = 0; var4 < var3; ++var4) {
String i = var2[var4];
System.out.println(i);
}
ArrayList<String> list = new ArrayList();
list.add("111");
list.add("222");
list.add("333");
Iterator var7 = list.iterator();
while(var7.hasNext()) {
String i = (String)var7.next();
System.out.println(i);
}so , Traversing the array uses the original for loop , The collection uses Iterator iterator . The latest interview questions have been sorted out , You can Java Interview library applet online brush questions .
(2) Remove elements
Oh, yes k! Next, let's delete the element :
Use for loop :
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
log.info(list.toString());
for (int i = 0; i <list.size(); i++) {
list.remove("222");
}
log.info(list.toString());11:11:52.532 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]
11:11:52.539 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 333]Use foreach:
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
log.info(list.toString());
for (String i : list) {
list.remove("222");
}
log.info(list.toString());11:50:48.333 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.xiaolinge.com.hello.HelloWord.main(HelloWord.java:30)Obviously, wood has success !
Click on the official account ,Java dried food Timely delivery 
reason :
Every traversal inside the iterator will record List Inside modcount As expected , Then use the expected value and in each cycle List Member variables of modCount The comparison , But ordinary list.remove It's called List Of remove, At this time modcount++, however iterator The expected value recorded in = There is no change , So there's an error .
If you want to delete an element, you need to use the inside of the iterator remove Method :
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
log.info(list.toString());
Iterator<String> it = list.iterator();
while (it.hasNext()){
String next = it.next();
//if For external use list Of remove The method will still report an error
if(next.equals("222")){
it.remove();// Here we use the inside of the iterator remove() Method ,
// Of course if you use list Of remove If the method deletes texture elements here, it is successful , such as :list.remove("222")
}
}
log.info(list.toString());result :
12:06:14.042 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]
12:06:14.046 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 333](3) Modifying elements
Use primitive for:
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
log.info(list.toString());
for (int i = 0; i <list.size(); i++) {
list.set(i,"444");
}
log.info(list.toString());result :
12:12:56.910 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]
12:12:56.915 [main] INFO com.xiaolinge.com.hello.HelloWord - [444, 444, 444]Oh, yes k! You can modify elements ;
Use foreach:
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
log.info(list.toString());
for (String i : list) {
i="444";
}
log.info(list.toString());result :
12:34:47.207 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]
12:34:47.211 [main] INFO com.xiaolinge.com.hello.HelloWord - [111, 222, 333]See , No way .
Spicy? , You can't modify elements , Can you modify the attributes of an element ? Let's take a look . The latest interview questions have been sorted out , You can Java Interview library applet online brush questions .
(4)foreach Modify element properties
(for I won't test it )
public class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public Student(){};
public Student(int age,String name){
this.age=age;
this.name=name;
}
}Oh, yes k, Next, test the code :
Student student=new Student(1,"huge");
Student student1=new Student(1,"xiaoyao");
List<Student> studentList=new ArrayList<Student>();
studentList.add(student);
studentList.add(student1);
System.out.println(student.getName());
System.out.println(student1.getName());
for(Student stu:studentList)
{
stu.setName("jingtian");
}
System.out.println(student.getName());
System.out.println(student1.getName());huge
xiaoyao
jingtian
jingtian484 Amazing ! Can't modify the object , But you can modify the properties of the object .
summary
for And foreach Can traverse arrays / aggregate , however for It is more efficient in more complex cycles .
foreach Cannot delete / Modify set elements , and for Sure
foreach and for You can modify the attributes in the element
So by comparison for More flexible loops .
Copyright notice : This paper is about CSDN Blogger 「coder Brother Xiao Lin 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement . Link to the original text :https://blog.csdn.net/qq_40521656/article/details/90749927


Spring Cloud Alibaba Finally unify the Jianghu !
Spring Boot After the scheduled task is started , How to stop automatically ?
23 Design mode and Practice ( Very comprehensive )
Spring Boot Protect sensitive configurations 4 Methods !
Face a 5 year Java, Neither thread can exchange data !
Why does Ali recommend LongAdder?
A new technical director : No code writing with headphones ..
Don't use it. System... It's time ,StopWatch Good use of explosion !
Java 8 Sort of 10 A pose , What a show !
Spring Boot Admin Born in the sky !
Spring Boot Learning notes , This is so complete !
Focus on Java Technology stack, see more dry goods


Spring Cloud Alibaba The latest combat !
边栏推荐
- VIM命令模式与输入模式切换
- Easyui学习整理笔记
- When initializing 'float', what is the difference between converting to 'float' and adding 'f' as a suffix?
- Hash / (understanding, implementation and application)
- 博客搬家到知乎
- vim 的各种用法,很实用哦,都是本人是在工作中学习和总结的
- The use of list and Its Simulation Implementation
- After the uniapp jumps to the page in onlaunch, click the event failure solution
- Network protocol concept
- R Language Using Image of magick package Mosaic Function and Image La fonction flatten empile plusieurs images ensemble pour former des couches empilées sur chaque autre
猜你喜欢

Antd select selector drop-down box follows the scroll bar to scroll through the solution
![[untitled]](/img/f9/18b85ad17d4c560f2b9d95a53ee72a.jpg)
[untitled]

Use metersphere to keep your testing work efficient
![[untitled]](/img/a0/29975bc0f9832e1640cc39dfce4a71.jpg)
[untitled]

PostgreSQL中的表复制

基于华为云IOT设计智能称重系统(STM32)

Unsupervised learning of visual features by contracting cluster assignments
![[untitled]](/img/c7/b6abe0e13e669278aea0113ca694e0.jpg)
[untitled]

Array object sorting

高考作文,高频提及科技那些事儿……
随机推荐
Hash / (understanding, implementation and application)
技术分享 | 抓包分析 TCP 协议
Une fois que l'uniapp a sauté de la page dans onlaunch, cliquez sur Event Failure resolution
electron 添加 SQLite 数据库
Antd select selector drop-down box follows the scroll bar to scroll through the solution
网络协议 概念
RationalDMIS2022阵列工件测量
STM32 entry development NEC infrared protocol decoding (ultra low cost wireless transmission scheme)
The annual salary of general test is 15W, and the annual salary of test and development is 30w+. What is the difference between the two?
通过 Play Integrity API 的 nonce 字段提高应用安全性
RationalDMIS2022 高级编程宏程序
PostgreSQL中的表复制
QT | multiple windows share a prompt box class
Vscode 尝试在目标目录创建文件时发生一个错误:拒绝访问【已解决】
Electron adding SQLite database
MIF file format record
oracle常见锁表处理方式
How to remove addition and subtraction from inputnumber input box
From pornographic live broadcast to live broadcast E-commerce
正在运行的Kubernetes集群想要调整Pod的网段地址