虽然使用for循环而不是Iterator遍历ArrayList,为什么输出引用的是地址而不是实际的对象?

问题描述 投票:0回答:1

我从用户定义的班级中的对象创建了一个列表,这些对象称为学生。

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

我不知道为什么会这样。

我已经从我的用户定义类中称为“学生”的对象创建了一个列表。班级学生{字符串名称,电话,组;学生(字符串名称,字符串电话,字符串组){this.name = ...

java arraylist
1个回答
2
投票

只需提取名称字段:

© www.soinside.com 2019 - 2024. All rights reserved.