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

时间:2013-12-05 03:34:31

标签: java list collections arraylist

我想通过使用ArrayList动态添加多个学生数据,但它显示错误的打印  e.g

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;
            }

PLZ帮助解决这个问题

6 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

目前,您正在从toString()获取java.lang.Object方法 - 其中包括类和参考地址。听起来像你要覆盖(并且你可以覆盖)学生中的toString()方法有这样的东西

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

答案 2 :(得分:1)

而不是行:

for (int i = 0; i < myArrayList.size(); i++) { 
    System.out.println(myArrayList.get(i));
}

使用常规循环:

for (int i = 0; i < myArrayList.size(); i++) { 
    System.out.println(myArrayList.get(i).iRollNum+" - "+myArrayList.get(i).strName);
}

OR高级循环:

for (Student student: myArrayList) { 
    System.out.println(student.iRollNum+" - "+student.strName);
}

这将打印输出,如:

4 - 阿莎

4 - 阿莎

4 - 阿莎

4 - 阿莎

4 - 阿莎

您需要使用以下命令指向Student类型ArrayList中的特定对象:

myArrayList.get(i)

然后打印您需要使用的对象变量

.iRollNum or .strName

在for循环中你创建一个对象Student student,这样你就可以使用该对象直接引用对象的变量/函数

你也可以使用@Paperwaste覆盖toString方法的方法 - 做同样事情的优雅方式。

答案 3 :(得分:0)

myArrayList.get(1)返回一个学生对象。当试图打印它时,它调用默认的toString()方法。你需要包含一个toString方法。尝试将此方法添加到您的学生班

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

答案 4 :(得分:0)

替换以下代码:

for (int i = 0; i <myArrayList.size(); i++) {   
       System.out.println(myArrayList.get(i));
}

用这个:

for (Student student : myArrayList ){
 System.Out.Println(student.toString());
}

或者如果你没有toString方法,你可以使用student.get&lt;&gt;获取所需值的方法

答案 5 :(得分:0)

我有Student类的另一个参数作为标记,它类似于数组:

int[] marks = new int[]{90, 80, 99, 95};

在这种情况下,我们需要使用toString()方法来打印数组结果。

相关问题