java - 如何使用ArrayList动态添加多个学生数据?

标签 java list collections arraylist

我想使用ArrayList动态添加多个学生数据,但它显示错误的打印 例如

STD.Student@1a2760f STD.Student@f4d6b3

public class Student {
            String strName;
            int iRollNum;


    public static void main(String[] args) {        



    ArrayList<Student> myArrayList=new ArrayList<Student>();
        Student student=new Student("Asha",4);
        myArrayList.add(student);
        Student student2=new Student("Asha",4);
        Student student3=new Student("Asha",4);
        Student student4=new Student("Asha",4);
        Student student5=new Student("Asha",4);
        myArrayList.add(student2);
        myArrayList.add(student3);
        myArrayList.add(student4);
        myArrayList.add(student5);

        for (int i = 0; i <myArrayList.size(); i++) {   


    System.out.println(myArrayList.get(i));
            }


            }

                public Student(String strName, int iRollNum) {
                this.strName = strName;
                this.iRollNum = iRollNum;
            }

请帮忙解决这个问题

最佳答案

@Override
public String toString() {
    return "("+strName+", "+iRollNum+")";
}

将此方法添加到 Student。 println 使用 toString 来确定如何显示字符串。默认情况下,它只显示类名称和一个随机数字。

关于java - 如何使用ArrayList动态添加多个学生数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390897/

相关文章:

java - 部署 servlet 时遇到问题。(intellij ultimate)

java - 单击 'create new account' 时应用程序崩溃

java - 如何在服务器端查找手机型号和制造商名称?

python - 对 NumPy 数组中的连续值切片求和

java - 如何设置 Struts 从 Collection 中选择标签的默认值

java - 如何在 Java 中关闭隐式流?

Java 多态性和列表

python - 如何在 Python3 中找到给定排行榜的排名?

objective-c - 我应该总是检查 [[NSArray alloc] init ...] 是否返回 nil 吗?

java - 如何使用 java 反射返回包含对象以外的内容的集合