理解java中的布尔值!array[i]
http://introcs.cs.princeton.edu/java/14array/CouponCollector .java.html
好的,据我了解,如果
boolean[] found = new boolean
未初始化,则为其分配默认的布尔值,即 false。但由于 false 的负数为 true (!found[val]
),当所有布尔值都设置为默认值 (false) 时,此条件如何起作用?提前致谢。
http://introcs.cs.princeton.edu/java/14array/CouponCollector.java.html
Okay, so from what I understand, if
boolean[] found = new boolean
is not initialized, it is assigned with the default boolean value, which is false. But since the negatron of false is true (!found[val]
), how is it that this condition works when all of the boolean values are set to default (false)? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里没有什么神秘的。我认为你只是没有仔细阅读代码。以下是相关片段及其“含义”。
found
的所有元素最初都是 false。 (注释记录了found
数组的不变量。)如果
!found[val]
为 true(即found[val]
为仍然为 false)增加计数器……并将
found[val]
设置为 true,这样我们就不会再次计算该 val。There's no mystery here. I think you just didn't read the code carefully. Here are the relevant snippets and what they "mean".
All elements of
found
are initially false. (The comment is documenting the invariant for thefound
array.)If
!found[val]
is true (i.e. itfound[val]
is still false) increment the counter ...... and set
found[val]
to true so that we don't count this val again.检查后,无论发生什么情况,
found[val]
都会设置为true
。所以if (!found[val])
基本上意味着“如果我以前没有见过这个val
”。最终结果是
valcnt
最终成为唯一val
的计数。After the check, regardless of what happens,
found[val]
is set totrue
. Soif (!found[val])
basically means "if i haven't seen thisval
before".The end result is that
valcnt
ends up being the count of uniqueval
s.第一次有假。
这会生成一个随机数,因此在此循环中可能会生成多个随机数,例如五个。当第一次生成 5 时,
found[5]
为 false,但第二次生成为 true,因此条件为 false,并且valcnt++;
将不再达到。There are false at first time.
this generates a random number so in this loop there may be generated more then one say fives. When 5 is generated at first time
found[5]
is false but in second time it's true so condition is false andvalcnt++;
won't be reached anymore.因为 'val' 是 0 到 N-1 之间的随机整数。相同的值可能在 while 循环中出现两次,并且您只想更新在该索引处找到的内容一次。
Because 'val' is a random integer between 0 and N-1. The same value might occur twice in the while loop and you want to update found at that index only once.