为什么在while循环中使用itrerator对象时需要类型转换? [英] Why type casting is required while using itrerator object in the while loop?

查看:67
本文介绍了为什么在while循环中使用itrerator对象时需要类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java.在使用 Iterator 编写遍历 ArrayList 的代码时,在将迭代器的对象与 next()函数一起使用之前,我必须使用类名.有人可以帮我吗?

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;
    }
}

推荐答案

使您的迭代器 UserId 类型(指定类型),即

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.

这篇关于为什么在while循环中使用itrerator对象时需要类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆