gpt4 book ai didi

java - Java 中是否存在与带有引用变量的 for-each 循环等效的方法?

转载 作者:行者123 更新时间:2023-12-01 07:35:31 25 4
gpt4 key购买 nike

在 C++ 中,可以在 for-each 语句中使用引用变量,例如for (int &e : vec) 其中 &e 是对 e 值的引用。这使得人们能够更改在 for-each 循环中与之交互的元素的值。 Java 中是否有等效的构造?

下面是如何在 C++ 的 for-each 循环中使用引用变量的示例。

#include <iostream>
#include <vector>

int main()
{
// Declare a vector with 10 elements and initialize their value to 0
std::vector<int> vec (10, 0);

// e is a reference to the value of the current index of vec
for (int &e : vec)
e = 1;

// e is a copy of the value of the current index of vec
for (int e : vec)
std::cout << e << " ";

return 0;
}

如果在第一个循环中未使用引用运算符 &,则对 1 的赋值将仅分配给作为副本的变量 e(而不是vec 的当前元素的引用),即 & 不仅可以从 vector 中读取数据,还可以在 for-each 循环中写入 vector 。

例如,以下 Java 代码不会修改原始数组,而只是修改一个副本:

public class test {

public static void main(String[] args) {
test Test = new test();

int[] arr = new int[10];

for (int e : arr) // Does not write to arr
e = 1;

for(int e : arr)
System.out.print(e + " ");
}
}

最佳答案

不,没有。无论如何,如果您在迭代时修改它们,大多数集合都会抛出 ConcurrentModificationException。

不过,没有什么可以禁止您修改集合中包含的对象:

for (Customer c : customers) {
c.setActive(false);
}

对于列表,您可以使用 ListIterator 在迭代时替换当前元素。请参阅http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html

关于java - Java 中是否存在与带有引用变量的 for-each 循环等效的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com