Java:这两个代码是一样的吗?(Java: Are these 2 codes the same?)

编程入门 行业动态 更新时间:2024-10-20 11:44:31
Java:这两个代码是一样的吗?(Java: Are these 2 codes the same?) for (Player p : players) { p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

for (int i = 0; i < players.size() ; i++) { Player p = players.get(i); p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

第二个代码会产生一个空指针异常,可以做些什么来使底部等价?

for (Player p : players) { p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

and

for (int i = 0; i < players.size() ; i++) { Player p = players.get(i); p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

The second code yeilds a null pointer exception, what can be done to make the bottom one equivalent ?

最满意答案

如果players是自定义java.lang.Iterable ,那么get()实现被破坏,或者无论如何,都会以意想不到的方式行为(与java.util.List的行为不同),我可以看到发生这种情况。

除此之外,我能想到的唯一事情就是你没有在你的代码中显示我们的东西会导致某些错误。

如果你这样做会发生什么?

for (Iterator<Player> playerIter = players.iterator(); playerIter.hasNext();) { Player p = playerIter.next(); p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

编辑:

只要阅读AZ的回应 ,它肯定有可能是size()也有奇怪的行为。

I can see this happening if players is a custom java.lang.Iterable who's get() implementation is broken, or at any rate, behaves in an unexpected manner (different from java.util.List's behavior).

Other that that, the only thing I can think of is that something you're not showing us in your code is causing something to go terribly wrong.

What happens if you do this?

for (Iterator<Player> playerIter = players.iterator(); playerIter.hasNext();) { Player p = playerIter.next(); p.addCard(deck.dealCard()); p.addCard(deck.dealCard()); }

Edit:

Just read AZ's response, and it's definitely possible that it's size() that has the odd behavior as well.

更多推荐

本文发布于:2023-07-31 02:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这两个   代码   是一样的   Java   codes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!