package Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// 1.创建3个Dog {name, age}对象,放入到ArrayList中,赋给List 引用
// 2.用迭代器和增强for循环两种方式来遍历
// 3.重写Dog 的toString方法,输出name和age
public class Collection01 {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Dog("A",10));
list.add(new Dog("B",1));
list.add(new Dog("C",2));
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next.toString());
}
System.out.println("-------------------------");
for(Object dog : list){//这里暂时只能放Object,因为返回是Object类型
System.out.println(dog.toString());
}
}
}
class Dog{
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
02-23
411
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-15
4068
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-13
364
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)