You're trying to execute code outside of executable context. Code can only be executed from a method, static initialiser or instance initialiser (Thanks NickC) context.
Try moving it into the main
method to start with...
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));
}
Updated based on feedback
Your first error Cannot make a static reference to the non-static field rayList
was generated because the rayList
was not declared static
, but you were trying to reference it from a static
context.
// 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));
}
rayList
is declared as a "instance" field/variable, meaning that it requires an instance of the declaring class (Student
) before it has meaning.
This could be resolved by...
Creating an instance of Student
in main
and accessing it via that instance, for example...
public static void main(String[] args) {
Student student = new Student(...);
//...
System.out.println(student.rayList.get(0));
}
Personally, I don't like this, rayList
doesn't really belong with Student
, it adds no value. Can you imagine having to create an instance of Student
before you add any to the List
?
I also don't like accessing instance fields directly, but that's a personal preference.
Making rayList
static
static ArrayList<Student> rayList = new ArrayList<Student>();
// Is static
public static void main(String[] args) {
//...
System.out.println(rayList.get(0));
}
This is a viable option, but would require more context before it could be deemed good or bad. I personally feel that static
fields can cause more problems than they solve, but again, that's a personal opinion and your context may deem a reasonable solution.
Or, you could create a local instance of the List
within the context of the static
method as seen in the first example.
public static void main(String[] args) {
ArrayList<Student> rayList = new ArrayList<Student>();
//...
System.out.println(rayList.get(0));
}
As I said, which one you choice to do will come down to you, I would personally prefer the last two, but that's me.