快捷导航

今天我在看结合迭代器Iterator的时候,为什么next()方法用确定的对象接收和

Iterator it = c.iterator();while(it.hasNext()){  Student stu = (Student) it.next();  System.out.println(stu);}或Iterator it = c.iterator();while(it.hasNext()){ Object obj =it.next(); System.out.println(obj);}

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员2

如果你不转成Student类型,那么这个变量就不能使用Student类的方法和变量,只能使用Object 提供的方法。
比如Student 中有一个getName()方法,如果你不把它转成Student 你就不能使用getName()。
若解惑,望采纳
回复

使用道具 举报

it.next()返回的都是Object,都是用Object接收的吧。
只不过Student stu = (Student) it.next();是在你确定it遍历的c中的对象都是Student类型的情况下,强制转换把Object类型的it.netx()转换为了Student类型。
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP