问题
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);
}
回答1:
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);
}
}
回答2:
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.
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
回答3:
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:
public ArrayList()
Constructs an empty list with an initial capacity of ten.
By default add(item)
method of ArrayList
add the element to the end of the list.
来源:https://stackoverflow.com/questions/5809496/instantiating-a-new-arraylist-then-adding-to-the-end-of-it