简体   繁体   中英

How to print an ArrayList? - java

Question will be below.

public class University {
ArrayList<Student> students;

public University() {
    students = new ArrayList<Student>();
}

public void addStudent(Student students) {
    this.students.add(students);
}}

public class Student {
String name;
String studentID;
static int studentNumber = 0;

Student(String name, String sID){
    this.name = name;
    this.studentID = sID;
    studentNumber++;
}}

public class TestUniversity {

public static void main(String[] args) {
    University universityRegister = new University(); 
    Student studentRegister = new Student("Rachel Green", "a1234");
    universityRegister.addStudent(studentRegister);
    
    studentRegister = new Student("Monica Geller", "a12345");
    universityRegister.addStudent(studentRegister);
    
    studentRegister = new Student("Ross Geller", "a1111");
    universityRegister.addStudent(studentRegister);
    
    System.out.println("Number of student in University: " + Student.studentNumber);        
}}

A. I created 3 classes, 1.Student, 2.University, 3.UniversityTester, in 3 different files.

B. I created 3 objects of type Studnet, and stored them in the University class as an ArrayList.

I would like to know how I can print the ArrayList of the students including all information from the UniversityTester class? In the future, I will create another object called Stuff and I will store it in the University class as an ArrayList stuffList. Therefore, I don't want to print the students list from class Student.

Override toString() method in Student class as follows:

import java.util.StringJoiner;

public class Student {
  String name;
  String studentID;
  static int studentNumber = 0;

  Student(String name, String sID) {
    this.name = name;
    this.studentID = sID;
    studentNumber++;
  }

  @Override
  public String toString() {
    return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
        .add("name='" + name + "'")
        .add("studentID='" + studentID + "'")
        .toString();
  }
}

Now you can print the array list as follows in TestUniversity:

System.out.println("Student Details: " + universityRegister.students);

Add this to your student class:

  @Override
  public String toString() {
    return String.format("Student: %s , StudentID: %s", name, studentID);
  }

And then you can print the entire array like this:

System.out.println("Students: " universityRegister.students);

//Or like this:

for(Student st: universityRegister.students){
 System.out.println(st);
}

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