我已经从名为“学生”的用户定义类中的对象创建了一个列表。
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/