我现在正在学习java。在编写遍历代码时ArrayList
using Iterator
在使用迭代器的对象之前,我必须使用类名next()
功能。有人能帮我解决这个问题吗?
import java.util.*;
public class arraylistwithuserdefinedclass {
public static void main(String[] args) {
ArrayList<UserId> details=new ArrayList<UserId>();
UserId a= new UserId(22,"gurmeet");
UserId b= new UserId(24,"sukhmeet");
details.add(a);
details.add(b);
Iterator itr = details.iterator();
while(itr.hasNext()) {
UserId ui = (UserId) itr.next();
System.out.println(ui.age +" " + "" + ui.name) ;
}
}
}
class UserId {
int age;
String name;
UserId(int a, String b) {
age=a;
name=b;
}
}
制作你的迭代器UserId
type(指定类型),即
Iterator<UserId> itr = details.iterator();
因为如果您不指定类型,它将如何理解要返回的内容。因此,出于通用目的,它将返回 Object 类型,这就是需要向下转换的原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)