【问题标题】:get the output of for loop and insert it into an arraylist in java获取for循环的输出并将其插入java中的arraylist
【发布时间】:2015-11-26 02:58:27
【问题描述】:

如何获取我的 for 循环的输出值并将它们添加到我的 arraylist 所以如果我的循环的输出是这样的 string1,string2,string3 我如何将它放入我的数组列表中

List<String> tpc = new ArrayList<>();
for(int i = 0; i < topics.length; i++) {
    topics[i] = topics[i].trim();
}

【问题讨论】:

  • tpc.add(topics[i]);把 if 放在你的 "topics[i] = topics[i].trim();" 之后
  • 顺便说一句,您应该将 tpc 声明为 ArrayList 而不是 List
  • @WilliamKu No. List 如果他决定将实现更改为其他内容会更好。

标签: java loops arraylist


【解决方案1】:

您只需使用 ArrayList 类中包含的 add 方法。

ArrayList<String> tpc = new ArrayList<>();
for(int i = 0; i < topics.length; i++) {
    topics[i] = topics[i].trim();
    tpc.add(topics[i]);
}

这是一个如何将值插入到数组列表中的示例。

【讨论】:

    【解决方案2】:

    使用arraylist的add方法如下

    tpc.add(topics[i])
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2012-10-09
      • 1970-01-01
      • 2012-11-23
      相关资源
      最近更新 更多