【问题标题】:Why does this statement add a character at the end of collection?为什么这个语句在集合末尾添加一个字符?
【发布时间】:2016-06-03 01:17:40
【问题描述】:
    ArrayList<String> strings=new ArrayList<String>();
    strings.add("h");
    strings.add("e");
    strings.add("l");
    strings.add("l");
    strings.add("o");

下一条语句是strings.add(strings.remove(strings.size()-1)+"C");

那么输出结果就是[h,e,l,l,oC],

所以我想知道为什么strings.add(strings.remove(strings.size()-1)+"C")会得到这个结果,

【问题讨论】:

  • 不知道为什么投票结束的问题不清楚。
  • 那句话的哪一部分你不明白?
  • 请解释一下结果出乎意料。此外,最好在提问之前查阅文档。它将帮助您提出更高质量的问题,甚至可能回答您自己的问题。

标签: java string arraylist


【解决方案1】:

strings.remove(strings.size()-1) 返回“o”,因为ArrayList.remove 返回被删除的元素。然后“o”与“C”连接创建“oC”,该“oC”被添加到ArrayList的末尾

您可以认为strings.add(strings.remove(strings.size()-1)+"C"); 等同于:

String s = strings.remove(strings.size()-1);
// s is now equal to "o"
// strings is equal to ["h", "e", "l", "l"]
s += "C";
// s is now equal to "oC"
strings.add(s);
// strings is equal to ["h", "e", "l", "l", "oC"]

【讨论】:

  • 感谢您的回答。我现在明白了。
【解决方案2】:

strings.remove() returns the removed element to the calling place.

删除此列表中指定位置的元素(可选操作)。将任何后续元素向左移动(从它们的索引中减去 1)。返回从列表中移除的元素。

在这种情况下,它返回“o”。然后你将它与'C'连接起来。 结果是“oC”

您的最后一条语句是将这个“oC”添加到strings arraylist。

【讨论】:

  • 这个答案与投票赞成的答案有何不同?
  • 他们几乎同时得到了答复。 FGITW FTW
  • @Michael 我在手机上,所以我花了一点时间输入它,而上面的答案已经出现了。
  • 感谢您的回答。我现在明白了。
猜你喜欢
  • 2016-04-26
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
相关资源
最近更新 更多