Instantiating a new arraylist then adding to the end of it

浪尽此生 提交于 2019-12-24 01:53:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!