user695696
user695696

Reputation: 155

Instantiating a new arraylist then adding to the end of it

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

    }

Upvotes: 2

Views: 12792

Answers (3)

eldjon
eldjon

Reputation: 2840

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.

Upvotes: 0

Ishtar
Ishtar

Reputation: 11662

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

Upvotes: 3

thomas
thomas

Reputation: 61

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

Upvotes: 1

Related Questions