繁体   English   中英

如何打印数组列表

[英]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.

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