问题
I am learning java right now. While writing code for traversing ArrayList
using Iterator
I have to use the class name before using the iterator's object with next()
function. Can anybody help me with this?
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;
}
}
回答1:
Make your Iterator UserId
type (specify the type), ie
Iterator<UserId> itr = details.iterator();
Because if you don't specify the type, how will it understand what to return. So for generalized purpose it will return Object type and thats why downcasting is required.
回答2:
You have to specify the generic type for the Iterator because without this type the Iterator holds type Object :
Iterator itr = details.iterator();// This holds type Object.
for that it is required to cast every Object.
another reference :
it.next() Returns the next object. If a generic list is being accessed, the iterator will return something of the list's type. Pre-generic Java iterators always returned type Object, so a downcast was usually required.
it is not required if you set the type for the Iterator :
Iterator<UserId> itr = details.iterator();
// ^^--------------------------
So you can use without casting :
while (itr.hasNext()) {
UserId ui = itr.next();
//-------------^
回答3:
Your iterator is declared raw, that is the reason why you need to cast, do instead declare the iterator as a UserId doing Iterator<UserId>
Iterator<UserId> itr = details.iterator();
while(itr.hasNext()) {
...
UserId ui = (UserId)
来源:https://stackoverflow.com/questions/44341995/why-type-casting-is-required-while-using-itrerator-object-in-the-while-loop