assassinweed2 assassinweed2 - 23 days ago 6
Java Question

Adding to an ArrayList of a class object?

public static ArrayList<Lecturer> lecturers = new ArrayList<Lecturer>();
lecturers.add(Lecturer);

public Lecturer (String name, String id, String address, String email, String office, String phone_number, String research, Module mod){
super(name, id, address, email, office, phone_number);
this.research = research;
this.mod = mod;
}


Hi all,
I have created a class and a constructor called Lecturer which stores details about Lecturers. I have also created an ArrayList of the type Lecturer which stores objects of lecturers. However, when I try to add to the list I keep getting the error " expected". I know there is something wrong with the "add(Lecturer)" part but I can't seem to figure out what else to write instead. Any help would be appreciated, thank you.

Answer

Try adding real instances (and inside a method):

public void addLecturer(...) {
  // 
  lecturers.add(new Lecturer(....));
}

A more complete version

class Lecturers {

  public static ArrayList<Lecturer> lecturers = new ArrayList<Lecturer>();

  public static void addLecturer(Lecturer lecturer) {
    lecturers.add(lecturer);
  }

  public static void main(String[] args) {
    Lecturer one = new Lecturer(...)
    addLecturer(one);
  }
}


// you should extend a super Lecturer type
class Lecturer extends ... {

public Lecturer(String name, String id, String address, String email,   String office, String phone_number, String research, Module mod) {
    super(name, id, address, email, office, phone_number);
    this.research = research;
    this.mod = mod;
  }
}