简体   繁体   中英

How do I iterate over a class object that is declared as an ArrayList in another class?

So I have 2 classes: ClassRoom and Student .

In ClassRoom, I create an Arraylist using a Student type:

public class ClassRoom{
    int classID;
    String className;
    ArrayList<Student> studList = new ArrayList<>();

    public ClassRoom(int classID, String className){
        this.classID = classID;
        this.className = className;
    }

    public String toString(){
        return ("Class ID: " + classID + " Class name: " + className + " Students list: " + studList);
    } 

I also have 2 functions. One adds a student to the list and the other sends a message to each student's phone number. This is where I'm kinda stuck.

    public void addStudent(int studID, String studName, int studPhoneNum){
        Student stud = new Student(studName, studID, studPhoneNum);
        studList.add(stud);
        System.out.println(studList);
    }

    public void sendMessage(int studPhoneNum){
        for (Student phone : studList[studPhoneNum]) {
            System.out.println("Sending message to: " + phone);
        }
    }

I'm trying to understand how to iterate over the value studPhoneNum that is in the studList arraylist.

I get this error when I'm trying to do what I pasted here: The type of the expression must be an array type but it resolved to ArrayList<Student>

I'd love to know how to solve this.

Thanks

The answer is simple. An ArrayList is not an array. To access an item in an ArrayList , use [your_array_list].get([your_index])

So to iterate over an ArrayList you can use

for(Student student: studList)
{
  System.out.println("Sending message to: " + student);
}

or

for(int i=0; i < studList.size(); ++i)
{
  System.out.println("Sending message to: " + studList.get(i));
}

Consider using Streams to optimize your coding:

public void sendMessage(int studPhoneNum){
  Student student = studList.stream().filter(student-> student.studPhoneNum == studPhoneNum).findFirst().get();
  System.out.println("Sending message to: " + student.studName + " at " + student.studPhoneNum);
}

You can see the entire thing in practice here: https://repl.it/@randycasburn/Stream-Filter?language=java10&folderId=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM