Traversing a collection element using the iterator interface
Speaker: Wang Shaohua QQ Group No.: 483773664
Learning Goals:
1 Mastering using the iterator interface to traverse collection elements
I. Overview of iterator
The iterator interface is primarily used for traversal, so the iterator object is also known as an iterator. The following three methods are defined in the iterator interface:
Boolean hasnext (): Returns True if the collection element that is iterated has not been traversed yet
Object Next (): Returns the next element in the collection
void Remove (): Deletes the element returned by the previous next method in the collection
Second, using iterator to traverse the pet collection
12345678910111213141516171819202122232425262728293031 |
public class Test {
public static void main(String[] args) {
// 1、创建四个狗狗对象
Dog ououDog =
new Dog(
"欧欧"
,
"雪娜瑞"
);
Dog yayaDog =
new Dog(
"亚亚"
,
"拉布拉多"
);
Dog meimeiDog =
new Dog(
"美美"
,
"雪娜瑞"
);
Dog feifeiDog =
new Dog(
"菲菲"
,
"拉布拉多"
);
// 2、创建ArrayList集合对象并把四个狗狗对象放入其中
List dogs =
new ArrayList();
dogs.add(ououDog);
dogs.add(yayaDog);
dogs.add(meimeiDog);
dogs.add(
2
, feifeiDog);
// 添加feifeiDog到指定位置
// 3、输出集合中狗狗的数量
System.out.println(
"共计有" + dogs.size() +
"条狗狗。"
);
// 4、通过遍历集合显示各条狗狗信息
//4.1 获得集合中的迭代器 Learn from Teacher Wang Set (iii): Traversing collection elements using the iterator interface |