java - 当使用 for 循环而不是 Iterator 迭代 ArrayList 时,为什么输出引用的是地址而不是实际对象?

标签 java arraylist

我已经从名为“学生”的用户定义类中的对象创建了一个列表。

class Student {
    String name, phone, group;

    Student(String name, String phone, String group) {
        this.name = name;
        this.phone = phone;
        this.group = group;
    }
}

并通过以下方式访问它:

public static void main(String[] args) {
        Student s1 = new Student("Ayush", "9841293412", "L1N1");
        Student s2 = new Student("Rahul", "9842432423", "L1M1");
        Student s3 = new Student("Gaurav", "984129231", "L1N2");

ArrayList<Student> al = new ArrayList<Student>();
    al.add(s1);
    al.add(s2);
    al.add(s3);
    al.add(s4);
    al.add(s5); 

   for(Student name:al){
       System.out.println("Name: " + name);
    }

但输出引用对象如下:

Name: Student@1baf61
Name: Student@b5272

我不知道为什么会发生这种情况。

最佳答案

只需提取名称字段即可:

class Student {
    String name, phone, group;

    Student(String name, String phone, String group) {
        this.name = name;
        this.phone = phone;
        this.group = group;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", group='" + group + '\'' +
                '}';
    }

    public static void main(String[] args) {
        Student s1 = new Student("Ayush", "9841293412", "L1N1");
        Student s2 = new Student("Rahul", "9842432423", "L1M1");
        Student s3 = new Student("Gaurav", "984129231", "L1N2");

        ArrayList<Student> al = new ArrayList<Student>();
        al.add(s1);
        al.add(s2);
        al.add(s3);

        for (Student name : al) {
            System.out.println("Name: " + name.name);
            System.out.println("Name: " + name.getName()); // Using a getter
            System.out.println(name); // Using toString
        }
    }
}

最佳实践是使用 getter 或 toString 实现来更好地表示您的模型

关于java - 当使用 for 循环而不是 Iterator 迭代 ArrayList 时,为什么输出引用的是地址而不是实际对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60473902/

相关文章:

java - 如何使用@JsonProperty反序列化JSON响应?

java - 无法使用 OWASP.ESAPI 缓解 SQL 注入(inject) - Veracode

android - 在android中使用Arraylist搜索字符串

java - 如何根据另一个ArrayList对ArrayList进行排序?

java - 访问由字符串和数组组成的对象内的数组

java - 如何在java中获取录制的声音(音调)的频率值?

java - 对 Graphics2D 对象进行 HitTest ?

java - 达尔维克虚拟机 : Could not find class 'android. *

java - ArrayList容量增量方程

java - List<String> list = new ArrayList<String>() 和 ArrayList<String> list = new ArrayList<String>() 有什么区别?