gpt4 book ai didi

java - 类数组列表的迭代器

转载 作者:行者123 更新时间:2023-11-29 09:52:55 27 4
gpt4 key购买 nike

我是 Java 新手,所以如果我的问题看起来很愚蠢,请多多包涵。

我正在学习集合,我编写了一个程序来存储学生姓名 id 和标记。我将所有这些存储在 Arraylist 中。使用 for 循环我可以在我的程序中打印值。但是我不知道如何使用迭代器来做到这一点。我的代码是这样的。

学生.Java

public class Student{
private String name;
private String rollno;
private String biology;
private String maths;
private String science;

public Student(String name,String rollno,String biology,String maths,String science){
setName(name);
setRollno(rollno);
setBiology(biology);
setMaths(maths);
setScience(science);
}

public void setRollno(String rollno){
this.rollno=rollno;
}

public String getRollno(){
return rollno;
}

public void setName(String name){
this.name=name;
}

public String getName(){
return name;
}

public void setBiology(String biology){
this.biology=biology;
}

public String getBiology(){
return biology;
}

public void setMaths(String maths){
this.maths=maths;
}

public String getMaths(){
return maths;
}

public void setScience(String science){
this.science=science;
}

public String getScience(){
return science;
}


}

College.Java 是我的主要类(class)

import java.util.*;

public class College{

public static void main(String args[]){

ArrayList<Student> details = new ArrayList<Student>();
Student Jb=new Student("Jb ","417","92","97","90");
Student Laxman=new Student("Lucky","418","93","97","96");
Student Ajay=new Student("AJ ","419","89","95","93");
Student Venky=new Student("Venky","420","96","90","91");
Student Satti=new Student("Satti","421","70","94","96");

details.add(Jb);

details.add(Laxman);
details.add(Ajay);
details.add(Venky);
details.add(Satti);

for(int i=0;i<details.size();i++)
{
Student student=details.get(i);

System.out.println("Student Name : "+student.getName()+" Roll Number : "+student.getRollno()+" Biology : "+student.getBiology()+" Maths : "+student.getMaths()+" Science : "+student.getScience());

}
}
}

在这种情况下,我得到了正确的输出。

如果我删除 for 循环并用迭代器替换。我收到一些错误消息,提示 Object cannot be converted as Student

这是我的代码

ListIterator itr=details.listIterator();
while(itr.hasNext())
{
//Object student=itr.next();
Student student=itr.next();
System.out.println("Student Name : "+student.getName()+" Roll Number : "+student.getRollno()+" Biology : "+student.getBiology()+" Maths : "+student.getMaths()+" Science : "+student.getScience());
}

请指导我这里有什么问题以及如何更正。

最佳答案

正如你所拥有的,你必须显式地转换它:

 Student student=(Student)itr.next();

或更改您的 ListIterator 以使用泛型

ListIterator<Student> itr=details.listIterator();

但另一个更容易阅读的替代方法是 foreach 循环

for (Student student : details) {
System.out.println("Student Name : "+student.getName()+" Roll Number : "+student.getRollno()+" Biology : "+student.getBiology()+" Maths : "+student.getMaths()+" Science : "+student.getScience());
}

关于java - 类数组列表的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30860726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com