我想使用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/