对如何实现ArrayList感到困惑

时间:2018-11-26 04:39:19

标签: java arraylist implementation

所以我一直在看ArrayLists,并且困惑于如何向数组中添加元素,而没有为每个对象一遍又一遍地明确说明people.add(person1)。我目前正在编译此代码,但在控制台中未打印任何内容。我认为我的错误与对象构造函数和people.add(this)有关。我在做什么错了?


import java.util.ArrayList;

public class People {

  int age;
  String name;

  static ArrayList<People> people = new ArrayList<People>();

  public People(String name, int age){
    this.name = name;
    this.age = age;
    people.add(this);
  }    

  People person1 = new People("Bob", 41);
  People person2 = new People("Arthur", 32);
  People person3 = new People("Tom",18);

  public static void main(String[] args){

    for(People p : people) {
      System.out.println(p.name);
    }
  }
}

3 个答案:

答案 0 :(得分:0)

数组列表是一个static变量。您正在创建的People对象是非静态变量,仅在调用构造函数时才创建。您应该将对象创建移至main()函数中。

public static void main(String[] args){
  People person1 = new People("Bob", 41);
  People person2 = new People("Arthur", 32);
  People person3 = new People("Tom",18);

    for(People p : people) {
      System.out.println(p.name);
    }
  }

您可以了解有关静态变量here

的更多信息

答案 1 :(得分:0)

您的代码有些复杂。要使用ArrayList,可以在main方法中声明ArrayList,然后在其中创建People类的对象,并在ArrayList中添加people对象。在People类中创建People类的这三个实例的方式中,创建People对象将导致指向StackOverflowError的循环引用。

您应将代码修改为类似的内容,并注意为People对象打印有意义的信息,您将需要重写Object类中的toString方法,否则它将仅打印对象地址,而这可能对您来说是垃圾。

public class People {

    int age;
    String name;

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("age: %s, name: %s", age, name);
    }

    public static void main(String[] args) {
        ArrayList<People> people = new ArrayList<People>();

        People person1 = new People("Bob", 41);
        People person2 = new People("Arthur", 32);
        People person3 = new People("Tom", 18);

        people.add(person1);
        people.add(person2);
        people.add(person3);

        people.forEach(System.out::println);
    }
}

尝试一下,如果您遇到任何问题,请告诉我。

答案 2 :(得分:-1)

尝试一下:

import java.util.ArrayList;

public class People {

  int age;
  String name;

  People(String name, int age){
    this.name = name;
    this.age = age;


    Main.people.add(this);
  }    

}

public class Main {

  public static ArrayList<People> people = new ArrayList<People>();

  public static void main(String[] args){

  People person1 = new People("Bob", 41);
  People person2 = new People("Arthur", 32);
  People person3 = new People("Tom",18);


    System.out.println(people.size());

    for(People p : people) {
      System.out.println(p.name);
    }
  }

}