将多个编号的对象添加到 ArrayList [英] Add multiple numbered objects to ArrayList

查看:23
本文介绍了将多个编号的对象添加到 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a lot of String Variables(100 for example):

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

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

I want to add these String variables to ArrayList, what I am doing now is

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

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

I am curious, is there a way to use a loop? For example.

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

推荐答案

使用数组:

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

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

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

This idea is so popular that there's built-in methods to do it. For example:

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

会将您的数组元素添加到现有列表中.如果你只想要一个只有数组元素的列表,你可以在一行上完成:

will add your array elements to an existing list. If you just want a list with only the array elements, you can do it on one line:

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

这篇关于将多个编号的对象添加到 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆