【发布时间】: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