【问题标题】:Can't print my objects on console from java arraylist无法从 java arraylist 在控制台上打印我的对象
【发布时间】:2023-02-04 23:18:49
【问题描述】:

即使在我向下转换之后,我也无法将我的对象从 arraylist 显示到控制台。请让我知道我哪里错了,我卡住了。在控制台中,学生姓名和 ID 均为 null 或 0 值。

import java.util.*;

//collestions (arrayList)

class Student{
    String Name;
    int Id;
    Student(String name,int id){
        name=this.Name;
        id=this.Id;
    }
    public void print(){
        System.out.println("Student name= "+Name);
        System.out.println("Student ID= "+Id);
    }
}

public class test6 {
    public static void main(String[] args) {
        Student s1 = new Student("Ali", 1);
        Student s2 = new Student("Raza",2);
        Student s3 = new Student("Saad",3);
        ArrayList<Student> al = new ArrayList<Student>();
        // now if we want to add an object in the arraylist we will use the add method.
        al.add(s1);
        al.add(s2);
        al.add(s3);
        //using some methods now checking if the arraylist is empty or not
        boolean b=al.isEmpty();
        if(b==true){
            System.out.println("Arraylist is empty");
        }
        else{
            System.out.println("Arraylist is not empty");
            int size = al.size();
            System.out.println("Arraylist size: "+size);
        }
        //Arraylist stores all the students or anything we store in it as object of the very big daddy class but if we want to get it and print it we need to downcast it and again change it into the student class object as 
        for(int i=0;i<al.size();i++){
            Student s = (Student) al.get(i);
            s.print();
        }

    }
}```

【问题讨论】:

  • 你最好覆盖 toString 并让它自己打印。在Java中使用@Override注解Variable names start lower case
  • 你的构造函数是问题所在。您正在将类字段的值分配给您的参数。

标签: java arrays arraylist collections printing


【解决方案1】:

将此代码添加到您的 Student 类。然后你可以简单地使用 System.out.println(student)。

@Override
public String toString(){
return "Name: " + this.Name + "
"
"Id: " + this.Id + ".";
}

我还建议您为字段创建 getter 和 setter。将“Name*”重命名为“name”,将“Id”重命名为“id”,并将它们设为私有。

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2023-01-14
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2019-02-11
    • 2019-07-19
    相关资源
    最近更新 更多