为什么我不能在Iterator上调用特定的类方法?
问题描述:
ArrayList array = new ArrayList();
Iterator it1 = array.iterator();
while (it1.hasNext()){
Myclass temp = it1.myGetterMethod();
System.out.println (temp);
}
这就是我想要实现的,但迭代器只返回一个通用对象。当我打电话给Object.getClass()
时,班级是Myclass
。这是否意味着Iterator不是泛型的,并且我需要在迭代不是Java字符串的对象时扩展Iterator类?为什么我不能在Iterator上调用特定的类方法?
答
您没有创建通用ArrayList。
尝试
ArrayList<MyClass> array = new ArrayList<MyClass>();
Iterator<MyClass> it1 = array.iterator();
while (it1.hasNext())
{
MyClass temp = it1.myGetterMethod();
System.out.println (temp);
}
答
您的代码会错过一些重要的事情,但你要做的第一件事是,要么投用Iterator.next()调用的返回值(在你的代码失踪)或使用泛型让编译器为你整理它。
的两个备选方案会是这个样子(没有尝试编译他们,但他们应该是基本上是正确的):
随着投:
ArrayList array = new ArrayList();
...
Iterator it1 = array.iterator();
while (it1.hasNext()){
Myclass temp = (Myclass)it1.next()
System.out.println (temp);
}
有了泛型:
ArrayList<Myclass> array = new ArrayList<Myclass>();
...
Iterator<Myclass> it1 = array.iterator();
while (it1.hasNext()){
Myclass temp = it1.next()
System.out.println (temp);
}
编辑:正如其他人指出的那样,在大多数情况下使用foreach构造更适合可读性。我决定只是尽可能少地修改你的初始代码。 A for构造看起来是这样的:
ArrayList<Myclass> array = new ArrayList<Myclass>();
...
for(Myclass temp : array){
System.out.println (temp);
}
答
更好地使用for语句,因此隐藏了迭代器的复杂性。它更容易阅读
for (MyClass temp: array)
{
System.out.println (temp);
}
您需要将'Iterator'泛化到'Iterator',否?或者直接到'for(MyClass c in array)'。 –
2010-02-19 22:08:17
@Michael Brewer-Davis:它会自动为您完成,具有泛型的集合将返回相应的迭代器。它需要被正确地声明。 – Fredrik 2010-02-19 22:12:04
@curlingdude:现在当你的答案被接受时,也许你应该考虑纠正它?您混合使用“MyClass”和“Myclass”,它在“Iterator it1”声明中完全省略。 – Fredrik 2010-02-19 22:19:54