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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:53:42  来源:igfitidea点击:

Instantiating a new arraylist then adding to the end of it

javaarraylist

提问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, Listinstead of ArrayListand this.so you never make that mistake again:

其可能的(或应该)的样子: privateList而不是ArrayListthis.,所以你永远不会再犯同样的错误:

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 ArrayListyou 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 ArrayListadd the element to the end of the list.

默认情况下add(item)ArrayList将元素添加到列表末尾的方法。