将字符串添加到 ArrayList [英] Adding Strings to an ArrayList
问题描述
我需要确保我正确地构建了这个程序.我必须编写一个使用 ArrayList 容器并在其中放入 5 个字符串的程序,然后从 ArrayList 中打印出 5 个字符串.我是 ArrayList 的新手,所以想确保我满足了要求.
I need to make sure I am building this program right. I have to write a program that uses an ArrayList container and put 5 Strings in it and then print out the 5 Strings from the ArrayList. I am new to ArrayList's so want to make sure I have the requirements fulfilled.
我的问题是:这是创建字符串、创建 ArrayList、将字符串添加到列表然后打印列表的正确方法吗?"
My question is: "Is this the proper way to Create Strings, Create an ArrayList, add the Strings to the List and then Print the List?"
public static void main(String[] args)
{
ArrayList<String> names_and_numbers = new ArrayList<>();
String bob = "bob";
String nancy = "nancy";
String jim = "jim";
String claire = "claire";
names_and_numbers.add( bob );
names_and_numbers.add( nancy );
names_and_numbers.add( jim );
names_and_numbers.add( claire );
for (String e : names_and_numbers)
{
System.out.println(e);
}
int six = 6;
String numbers = "";
ArrayList<Integer> myList = new ArrayList<>();
myList.add( 1 );
myList.add( 2 );
myList.add( 3 );
myList.add( 4 );
myList.add( 5 );
myList.add(six);
for (int x : myList)
{
System.out.println(x);
}
//System.out.println(myList);
//System.out.println(names_and_numbers);
}
}
推荐答案
你做得很好,我没有看到问题,但我认为 arraylists 存储对象,所以如果你想要一个整数,请构建一个对象.我想如果你能编译它,这会自动完成.
You're doing ok, I don't see a question but I think that arraylists store objects, so if you want an integer, get build an object. I guess if you can compli that, this is done automatically.
Integer i = new Integer(1);
myList.add(i);
或在 1 行中
myList.add(new Integer(1));
正如 Paul Bellora 所说,new Integer(i)
是不必要的,你可以只用 i
替换它.我只是想指出 ArrayLists store objects(不知何故我忘了提到这一点),而不是像 int
这样的原始数据类型,当你尝试这样做时,数据是如果可能的话(对编译器)转换为 Object
的子对象,就像 Integer
一样.
As Paul Bellora says, new Integer(i)
is unnecessary and you can replace it with just i
. I just wanted to point out that ArrayLists store objects (somehow i forgot to mention that), not primitive data types like int
and when you try to do it, the data is converted if possible (to the compiler) to a child of Object
just like Integer
.
这篇关于将字符串添加到 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!