在Java中,您能否在for循环中更改/设置变量的值?

huangapple go评论63阅读模式
英文:

In Java, can you change/set the value of the variable in a for loop?

问题

抱歉,如果我的术语不正确的话。

在Java中,如果我有一个类似以下形式的for循环:

Entry something_else = ....;
for (Entry x : entries) {
    x = something_else;
}

在上述for循环的循环体内将循环变量(x)设置为something_else是否合适/可以接受?

英文:

My apologies in advance if my terminology is incorrect.

In Java, if I have a for loop of the form:

    Entry something_else = ....;
	for (Entry x : entries) {
		x = something_else;
	}

is it kosher/ok to set that loop variable (x) to something_else inside the body of the for loop as above?

答案1

得分: 1

这段代码绝对等同于:

Entry something_else = ....;
for (Entry y : entries) {
    Entry x = y; // 对该对象引用的复制
    x = something_else; // 对 y 毫无影响
}

除此之外,它是有效的。

因此,这段代码可能会产生一些令人“惊讶”的效果,这可能不是作者的本意。

英文:

This code is absolutely equivalent to:

Entry something_else = ....;
for (Entry y : entries) {
    Entry x = y; // a copy of the reference to that object
    x = something_else; // has no effect whatsoever on y
}

Otherwise, it works.

So this code may do something surprising, which may not be what the author meant.

答案2

得分: 0

是的,这是可能的,但不是一个好主意。

更有意义的做法是创建另一个变量并赋予它新的期望值,从而消除任何可能的混淆。

我想不出有哪种情况下这样做会增加清晰度或任何其他好处。也许你有一个例子呢?

英文:

Yes, it is possible, but not a good idea.

It makes much more sense to just create another variable and give it the newly desired value, eliminating any possible confusion.

I can't think of a scenario where doing this adds clarity or any other benefit. Maybe you have an example?

huangapple
  • 本文由 发表于 2020年9月3日 08:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63715164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定