将多个编号的对象添加到 ArrayList

新手上路,请多包涵

假设我有很多字符串变量(例如 100):

    String str1 = "abc";
    String str2 = "123";
    String str3 = "aaa";
....
    String str100 = "zzz";

我想将这些String变量添加到ArrayList中,我现在做的是

    ArrayList<String> list = new ArrayList<String>();
    list.add(str1);
    list.add(str2);
    list.add(str3);
...
    list.add(str100);

我很好奇,有没有办法使用循环?例如。

 for(int i =  1; i <= 100; i++){
     list.add(str+i)//something like this?
}

原文由 CSnerd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 446
2 个回答

使用数组:

 String[] strs = { "abc","123","zzz" };

for(int i =  0; i < strs.length; i++){
     list.add(strs[i]);  //something like this?
}

这个想法非常流行,以至于有内置的方法可以做到这一点。例如:

   list.addAll( Arrays.asList(strs) );

会将您的数组元素添加到现有列表中。 Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList() 。例如:

 Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );

如果你只想要一个只有数组元素的列表,你可以在一行中完成:

   List<String> list = Arrays.asList( strs );

编辑:Java API 中的许多其他类都支持此 addAll() 方法。它是 Collection 接口的一部分。 Other classes like Stack , List , Deque , Queue , Set , and so forth implement Collection 因此 addAll() 方法。 (是的,其中一些是接口,但它们仍然实现 Collection 。)

原文由 markspace 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的是 Java 9,那么您可以轻松地将多个 String 对象添加到 Array List 中

List<String> strings = List.of("abc","123","zzz");

原文由 Noyal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题