java有段代码不是很明白
来源:百度知道 编辑:UC知道 时间:2024/05/29 02:12:07
ArrayList list = new ArrayList();
Cat cat = new Cat("cat_1");
list.add(cat);
list.add(new Cat("黑猫"));
Iterator it = list.iterator();
while (it.hasNext()) {
Cat c = (Cat) it.next();
c.show();
}
while (it.hasNext()) {
Cat c = (Cat) it.next();
c.show();
}
这句是迭代器循环读取信息嘛,
那Cat c=(Cat)it.next():是 Cat c=new Cat这个意思?
然后又it.next()这个方法?
Cat cat = new Cat("cat_1");
你给的不全吧。
你应该有个CLASS 是Cat 他的构造方法是带参数的
new Cat 就是生成个实体类
你可以调用
比如说
人 小白 = 人(“属性”);
就是这个意思
Cat c=(Cat)it.next():
强制转换成CAT类型 返回一个object对象,必要要这样做
我回答下啊~~~
首先请查看ipa文档
里面你会发现 List集合类 装的对象是 object类型
就是说可以装任何东西 ,无论是元数据还是对象 和是集合类对象
同时取的时候也的需要 转化为需要的对象 使用的方式 一般为 强化
所以这里Cat c = (Cat) it.next();
就是从集合类中取出 对象 object类型 然后强转为 Cat 类类型对象
public static void main(String[] args) {
ArrayList list = new ArrayList(); //声明集合list
Cat cat = new Cat("cat_1"); //实例化对象cat,并赋值
list.add(cat); //在list集合中添加Cat的对象cat
list.add(new Cat("黑猫")); //在list集合中添加Cat的对象
Iterator it = list.iterator(); //通过Iterator可以让list迭代
while (it.hasNext()) { //判断是否还有下一个元素,有就返回ture,没有就返回false
Cat c = (Cat) it.next();