[英]How to print an array list
我正在嘗試打印一個數組列表,但無法打印。 請幫忙。
包 com.company;
導入 java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
String harryPotter = new String();
Student hermoineG = new Student("Hermoine", "Granger", 12);
System.out.println(hermoineG.getFull());
Student ronW = new Student("Ron","Weasley",12);
System.out.println(ronW.getFull());
Student dracoM = new Student("Draco","Malfoy", 11);
System.out.println(dracoM.getFull());
Student lunaL = new Student("Luna", "Lovegood", 9);
System.out.println(lunaL.getFull());
Student nevilleL = new Student("Neville", "Longbottom",8);
System.out.println(nevilleL.getFull());
Student cedricD = new Student("Cedric","Diggory",12);
System.out.println(cedricD.getFull());
Student georgeW = new Student("George", "Weasley",10);
System.out.println(georgeW.getFull());
Student padmaP = new Student("Padma", "Patil", 11);
System.out.println(padmaP.getFull());
Student fredW = new Student("Fred", "Weasley", 8);
System.out.println(fredW.getFull());
School.addStudents(School.students, harryPotter);
System.out.println(hermoineG.getClass());
students.add(hermoineG);
System.out.println(students);
}
}
您可能想要使用循環:
for (Student student : students) {
System.out.println(student.getFull());
}
當您創建自己的類(如 Student)時,您需要覆蓋 Student 類中的 toString 方法,以便使用 System.out.println 進行打印。 將以下內容添加到您的 Student 類:
@Override
public String toString() {
return getFull();
}
這將允許 System.out.println(students); 正確打印ArrayList。 但就目前情況而言,列表中只有一名學生。
請注意,上面將顯示 Student 對象,因為它是在“getFull”方法中格式化的。 如果需要,您可以更改格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.