添加字符串到一个ArrayList [英] Adding Strings to an ArrayList

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

问题描述

我要确保我建立这个节目的权利。我必须写一个使用一个ArrayList容器程序,并把5中的字符串,然后从ArrayList中打印出5串。我是新来ArrayList的的所以想确保我有要求的满足。

我的问题是:这是创建字符串,创建一个ArrayList,将字符串添加到列表中,然后打印列表有道

 公共静态无效的主要(字串[] args)
{ArrayList的<串GT; names_and_numbers =新的ArrayList<>();
字符串BOB =鲍勃;
字符串南希=南希
字符串吉姆=吉姆;
字符串克莱尔=克莱尔names_and_numbers.add(BOB);
names_and_numbers.add(南希);
names_and_numbers.add(JIM);
names_and_numbers.add(克莱尔);对(串E:names_and_numbers)
{
 的System.out.println(E);
}诠释6 = 6;
串号=;ArrayList的<整数GT; myList中=新的ArrayList<>();myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(5);
myList.add(SIX);对于(INT X:myList中)
{
 的System.out.println(X);
}//System.out.println(myList);
//System.out.println(names_and_numbers);
}
}


解决方案

您正在做的不错,我没有看到一个问题,但我认为的ArrayList存储对象,所以如果你想要一个整数,得建立一个对​​象。我想如果你能compli的是,这是自动完成的。

 整数i =新的整数(1);
myList.add(ⅰ);

或在1行

  myList.add(新的整数(1));

编辑:

正如保罗Bellora说,新的整数(I)是不必要的,你可以只用替换I 。我只是想指出的ArrayList 存储对象的(不知怎的,我忘了提,),而不是基本数据类型,如 INT ,当你尝试做到这一点,将数据转换(如果可能的编译器),以对象的子就像整数

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.

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);   
}
}

解决方案

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);

Or in 1 line

myList.add(new Integer(1));

Edit:

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屋!

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