java 实例化一个新的数组列表,然后添加到它的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5809496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Instantiating a new arraylist then adding to the end of it
提问by user695696
public ArrayList<Person> people;
Is this how you would instantiate the people variable as a new empty ArrayList of Person objects?
这是将 people 变量实例化为 Person 对象的新空 ArrayList 的方式吗?
ArrayList<Person> people = new ArrayList<Person>();
And is this how you would add newMember to the end of the list?
这就是您将 newMember 添加到列表末尾的方式吗?
public void addItem(Person newMember){
people.add(newMember);
}
回答by Ishtar
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:
其可能的(或应该)的样子:
private
,List
而不是ArrayList
和this.
,所以你永远不会再犯同样的错误:
public class Foo {
private List<Person> people;
public Foo() {
this.people = new ArrayList<Person>();
}
public void addItem(Person newMember) {
people.add(newMember);
}
}
回答by thomas
Yes, that's correct. If you later wish to add an item to the middle of the list, use the add(int index, Object elem) method.
对,那是正确的。如果您稍后希望向列表中间添加一个项目,请使用 add(int index, Object elem) 方法。
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
回答by eldjon
In order to instantiate an empty ArrayList
you have to explicitly define the number of elements in the constructor. An empty constructor allocates memory for 10 elements. According to documentation:
为了实例化一个空的,ArrayList
你必须在构造函数中明确定义元素的数量。一个空的构造函数为 10 个元素分配内存。根据文档:
public ArrayList()
Constructs an empty list with an initial capacity of ten.
公共数组列表()
构造一个初始容量为 10 的空列表。
By default add(item)
method of ArrayList
add the element to the end of the list.
默认情况下add(item)
,ArrayList
将元素添加到列表末尾的方法。