对如何实现ArrayList感到困惑



所以我在看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);
}
}
}

数组列表是一个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);
}
}

你可以在这里阅读更多关于静态变量的

您的代码稍微过于复杂。为了使用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);
}
}

试试这个,如果你遇到任何问题,请告诉我。

试试这个:

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

最新更新