实例化一个新的ArrayList然后加入到它的结束 [英] Instantiating a new arraylist then adding to the end of it
本文介绍了实例化一个新的ArrayList然后加入到它的结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
公开的ArrayList<&人GT;人;
这是你将如何实例化人变量Person对象的一个新的空的ArrayList <?/ p>
的ArrayList&LT;&人GT;人=新的ArrayList&LT;&人GT;();
和这是如何添加newMember到列表的末尾?
公共无效的addItem(人newMember){
people.add(newMember); }
解决方案
否
类Foo {
公众的ArrayList&LT;&人GT;人; 美孚(){
//这个:
ArrayList的&LT;&人GT;人=新的ArrayList&LT;&人GT;();
//创建一个新的变量也称为人! 的System.out.println(this.people); //输出空!
的System.out.println(人); //输出bladiebla
}
美孚(){
人=新的ArrayList&LT;&人GT;(); //这并不工作
}
}
什么它可以(或应该)是这样的:私人
,列表
而不是的ArrayList
和<$ C $的C>这个,所以你永远不会再犯同样的错误。
公共类Foo {
私人列表&LT;&人GT;人; 公共美孚(){
this.people =新的ArrayList&LT;&人GT;();
}
公共无效的addItem(人newMember){
people.add(newMember);
}
}
public ArrayList<Person> people;
Is this how you would instantiate the people variable as a new empty ArrayList of Person objects?
ArrayList<Person> people = new ArrayList<Person>();
And is this how you would add newMember to the end of the list?
public void addItem(Person newMember){
people.add(newMember);
}
解决方案
No
class Foo {
public ArrayList<Person> people;
Foo() {
//this:
ArrayList<Person> people = new ArrayList<Person>();
//creates a new variable also called people!
System.out.println(this.people);// prints "null"!
System.out.println(people);//prints "bladiebla"
}
Foo() {
people = new ArrayList<Person>();//this DOES work
}
}
What it could(or should) look like:
private
, List
instead of ArrayList
and this.
so you never make that mistake again:
public class Foo {
private List<Person> people;
public Foo() {
this.people = new ArrayList<Person>();
}
public void addItem(Person newMember) {
people.add(newMember);
}
}
这篇关于实例化一个新的ArrayList然后加入到它的结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文