(可能很奇怪)长增量行为?

发布于 2025-01-03 06:14:37 字数 501 浏览 1 评论 0原文

我问这个问题有点尴尬,但以下代码片段的结果让我难住了:

System.out.println("incrementResultResponses() has been invoked!");
final long oldValue = resultResponses;
final long newValue = resultResponses++;
System.out.println("Old value = " + oldValue);
System.out.println("New value = " + newValue);

输出如下:

incrementResultResponses() has been invoked!
Old value = 0
New value = 0

为什么?并发会对这里的结果产生任何影响吗?顺便说一句,resultResponses 是一个long

I'm a bit embarrassed in asking this question, but the result of the following code snippet has me stumped:

System.out.println("incrementResultResponses() has been invoked!");
final long oldValue = resultResponses;
final long newValue = resultResponses++;
System.out.println("Old value = " + oldValue);
System.out.println("New value = " + newValue);

That outputs the following:

incrementResultResponses() has been invoked!
Old value = 0
New value = 0

Why? Would concurrency have any influence upon the result here? By the way, resultResponses is a long.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你与昨日 2025-01-10 06:14:37

后缀++运算符返回值(递增之前)。您想使用前缀 ++

final long oldValue = resultResponses++;
final long newValue = ++resultResponses;

The postfix ++ operator returns the old value (before incrementing). You want to use prefix ++:

final long oldValue = resultResponses++;
final long newValue = ++resultResponses;
枕花眠 2025-01-10 06:14:37

因为增量会在分配后增加值(后增量)。这正是 resultResponses++ 应该做的事情。
如果希望resultResponses为1,则需要使用Pre-Increment,即++resultResponses

Because the increment increases the value after it was assigned (Post-Increment). That's exactly what resultResponses++ is supposed to do.
If you want resultResponses to be 1, you need to use Pre-Increment, which is ++resultResponses

帅冕 2025-01-10 06:14:37

如果您想在赋值之前递增 oldValue,则必须在变量之前放置 ++

final long newValue = ++resultResponses;

这意味着递增发生在语句执行之前而不是之后。

If you want to increment oldValue before the assignment you will have to place ++ before the variable:

final long newValue = ++resultResponses;

This means that the increment takes place before the statement is executed instead of after.

冷夜 2025-01-10 06:14:37

请参阅 ,了解如何 postfixprefix 有效。
正如上面的答案中提到的,您可以使用这个:

final long oldValue = resultResponses;
final long newValue = ++resultResponses;

或者为了让它更漂亮,您也可以使用:

final long oldValue = resultResponses++;
final long newValue = resultResponses;

这也会产生相同的输出。

Refer this, to know how postfix and prefix work.
As mentioned in the above answers you can use this:

final long oldValue = resultResponses;
final long newValue = ++resultResponses;

Or to make it fancier you can also use:

final long oldValue = resultResponses++;
final long newValue = resultResponses;

which will also result in the same output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文