0

I have a program that creates a couple objects and adds each one to an ArrayList, then is supposed to loop over each object in the ArrayList and use a getter from another class within the project to display information on each object. I can't get the objects in my foreach loop to use any of the methods in my other class. Here is my main, including the trouble loop at the bottom:

import java.util.ArrayList;

public class ITECCourseManager {

    public static void main(String[] args) {

        ArrayList ITECCourse = new ArrayList();

        ITECCourse infotech = new ITECCourse("Info Tech Concepts", 1100, 5, "T3050");
        infotech.addStudent("Max");
        infotech.addStudent("Nancy");
        infotech.addStudent("Orson");
        ITECCourse.add(infotech);

        ITECCourse java = new ITECCourse("Java Programming", 2545, 3, "T3010");
        java.addStudent("Alyssa");
        java.addStudent("Hillary");
        ITECCourse.add(java);

        for (Object course : ITECCourse) {
            System.out.println("Name: " + course.getName());
        }
    }
}

And here is the other class in my project with the method I need to use:

public class ITECCourse {

    public String name;
    public int code;
    public ArrayList<String> students;
    public int maxStudents;
    public String room;

    ITECCourse(String courseName, int courseCode, int courseMaxStudents, String roomNum) {

        name = courseName;
        code = courseCode;
        maxStudents = courseMaxStudents;
        students = new ArrayList<String>();
        room = roomNum;
    }

    public String getName() {
        return name;
    }

If I replace course.getName() with java.getName(), the code works. I'm confused why I can't use a foreach loop across the ArrayList to use the getter for each object, when I am able to call the object and use the method directly from the same place in the code.

Edit: Thank you for the answers, simple mistake only had to make two/three changes: declare ArrayList<ITECCourse> at the beginning, change Object in for loop to ITECCourse, and of course change my arraylist from ITECCourse to ITECCourseList so there isn't confusion with my ITECCourse class.

admoore
  • 71
  • 1
  • 6

1 Answers1

2

The call to course.getName() doesn't work because you've defined course as an Object in your loop and Object doesn't have the method getName(). If you add a type parameter to your ArrayList declaration such as ArrayList<ITECCourse>, then you can iterate over the list of ITECCourse instances rather than Object.

On a side note, naming your variable ITECCourse will just lead to confusion because it's the same as your class. Might be better to name your variable something like itecCourseList.

Patrick Grimard
  • 7,033
  • 8
  • 51
  • 68