我的ArrayList无法识别我添加到列表中的内容

Ale*_*eer 0 java arraylist

这是代码本身

import java.util.ArrayList;

public class Student {
    private String name;
    private int age;

    public Student (String n, int a) {
        name = n;
        age = a;

    }

    public String toString() {
        return name + " is " + age + " years old";
    }

    ArrayList<Student> rayList = new ArrayList<Student>();
    rayList.add(new Student("Sam", 17));
    rayList.add(new Student("Sandra", 18));
    rayList.add(new Student("Billy", 16));
    rayList.add(new Student("Greg", 17));
    rayList.add(new Student("Jill", 18));

    public static void main(String[] args) {
        System.out.println(rayList.get(0));
    }

}
Run Code Online (Sandbox Code Playgroud)

main方法中缺少一些println命令.但是当我尝试将5个学生添加到我的ArrayList时,我收到错误"无法对非静态字段rayList进行静态引用"

Mad*_*mer 6

您正在尝试在可执行上下文之外执行代码.代码只能从方法,静态初始化程序或实例初始化程序(Thanks NickC)上下文执行.

尝试将其移入main方法开始...

public static void main(String[] args) {
    ArrayList<Student> rayList = new ArrayList<Student>();
    rayList.add(new Student("Sam", 17));
    rayList.add(new Student("Sandra", 18));
    rayList.add(new Student("Billy", 16));
    rayList.add(new Student("Greg", 17));
    rayList.add(new Student("Jill", 18));
    System.out.println(rayList.get(0));
}
Run Code Online (Sandbox Code Playgroud)

根据反馈更新

Cannot make a static reference to the non-static field rayList生成了第一个错误,因为rayList未声明static,但您尝试从static上下文引用它.

// Not static
ArrayList<Student> rayList = new ArrayList<Student>();
// Is static
public static void main(String[] args) {
    // Can not be resolved.
    System.out.println(rayList.get(0));
}
Run Code Online (Sandbox Code Playgroud)

rayList被声明为"实例"字段/变量,这意味着它需要一个声明class(Student)的实例才有意义.

这可以通过......解决

创建Studentin 实例main并通过该实例访问它,例如......

public static void main(String[] args) {
    Student student = new Student(...);
    //...
    System.out.println(student.rayList.get(0));
}
Run Code Online (Sandbox Code Playgroud)

就个人而言,我不喜欢这个,rayList并不属于真正属于它Student,它没有增加任何价值.你能想象Student在添加任何实例之前必须创建一个实例List吗?

我也不喜欢直接访问实例字段,但这是个人偏好.

制造 rayList static

static ArrayList<Student> rayList = new ArrayList<Student>();
// Is static
public static void main(String[] args) {
    //...
    System.out.println(rayList.get(0));
}
Run Code Online (Sandbox Code Playgroud)

这是一个可行的选择,但在被认为是好的或坏的之前需要更多的背景.我个人认为,static领域可能会导致比他们解决的更多问题,但同样,这是个人观点,您的背景可能认为是合理的解决方案.

或者,您可以Liststatic方法的上下文中创建本地实例,如第一个示例中所示.

public static void main(String[] args) {
    ArrayList<Student> rayList = new ArrayList<Student>();
    //...
    System.out.println(rayList.get(0));
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,你选择做哪一个会归结为你,我个人更喜欢最后两个,但那就是我.

  • 在我看来,编译器捕获的第一个错误是`rayList`不是静态的,而是从静态方法`main`引用的.我认为OP也应该知道这一点,尽管重要的是你也抓住了另一个错误. (2认同)