【问题标题】:How to add an element to an array without a modification of the old array or creation a new one?如何在不修改旧数组或创建新数组的情况下将元素添加到数组中?
【发布时间】:2010-03-22 14:40:04
【问题描述】:

我有以下构造:for (String playerName: players)

我想对所有players 加上一个特别的玩家进行循环。但我不想通过添加新元素来修改players 数组。那么,我该怎么办?

我可以将for (String playerName: players) 中的players 替换为包含players 的所有元素以及另外一个元素的内容吗?

【问题讨论】:

  • 你可以创建一个Iterable的实现,但是代码有点长和复杂。

标签: java arrays


【解决方案1】:

将循环的内容移动到另一个方法中,并在内部和外部调用它:

for (String playerName : players) {
    handlePlayer(playerName);
}
handlePlayer(anotherPlayerName);

【讨论】:

  • +1:这是最简单且恕我直言的最佳解决方案。无需创建新列表或更改旧列表的开销,它通过将代码移动到单独的函数中来改进代码。
  • @dbemerlin 开销 创建新列表?可能会很小(可能在 Apache Commons 中使用单个对象开销来实现)
【解决方案2】:

我同意@Bozhos 的回答是最好的解决方案。

但如果你绝对想使用单个循环,你可以使用Iterables.concat() from Google Collectons(连同Collections.singleton()):

Iterable<String> allPlayersPlusOne=Iterables.concat(players,Collections.singleton(other));
for (String player : allPlayersPlusOne) {
  //do stuff
}

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多