开发者

Instantiating a new arraylist then adding to the end of it

开发者 https://www.devze.com 2023-02-28 22:59 出处:网络
public ArrayList<Person> people; Is this how you would instantiate the people variable as a new empty ArrayList of Person objects?
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 y开发者_开发技巧ou 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);
  }
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消