How to create constructor with empty ArrayList?

44,505

Well, you want to pass an empty ArrayList, so pass an empty ArrayList:

class Student {
    String studentFirstName;
    String studentLastName;
    List<Course> studentSchedule; // no initialization here: it's done in the constructor

    // Constructors
    Student(String newFirstName,  String newLastName) {
        this(newFirstName, newLastName, new ArrayList<Course>());
    }

    Student(String newFirstName, String newLastName, List<Course> newSchedule) {
        this.studentFirstName = newFirstName;
        this.studentLastName = newLastName;
        this.studentSchedule = newSchedule;
    }

Note that you should generally declare the field as List<Course>, not as ArrayList<Course>, unless it's really important for the list to be an ArrayList, and not any other kind of list. Program on interfaces.

Also, your fields should be private, and shouldn't be named studentXxx. They're part of the Student class, so it's redundant. lastName is sufficient, and more redable.

Share:
44,505
rawr rang
Author by

rawr rang

Updated on March 09, 2020

Comments

  • rawr rang
    rawr rang about 4 years

    I wrote a constructors that can passes all the fields, including an Arraylist. I don't know what to do if I want constructors where I'm not passing the Arraylist and instead give it an empty Arraylist.

    For example I already wrote a Course class and now I'm writing a Student class. The student class contains an Arraylist.

    class Student {
        String studentFirstName;
        String studentLastName;
        ArrayList<Course> studentSchedule = new ArrayList<Course>();
    
        // Constructors
        Student(String newFirstName,  String newLastName) {
            this.Student(newFirstName, newLastName, _______ ); //what to put in the blank?
        }
    
        Student(String newFirstName, String newLastName, ArrayList<Course> newSchedule) {
            this.studentFirstName = newFirstName;
            this.studentLastName = newLastName;
            this.studentSchedule = newSchedule;
        }
        .
        .
        .
    

    I'm stuck here. Putting null in the blank does not work, I get compiler warning: The method Student(String, String, null) is undefined for the type Student Obviously I'm missing the point.

    How do I get the constructor to give me an empty Arraylist?

  • Erwin Bolwidt
    Erwin Bolwidt about 10 years
    'this.Student(' does not compile.
  • Marco13
    Marco13 about 10 years
    +1 for mentioning the List interface and best naming practices. One could additionally consider a defensive copy like this.studentSchedule = new ArrayList<Course>(newSchedule); to prevent the list from being modified after it has been passed to the constructor.