Traversing elements with a foreach loop
Speaker: Wang Shaohua QQ Group No.: 483773664
Learning Goals:
1. Master using the Foreach loop to iterate through the elements
JDK1.5 and later versions, you can iterate through the collection elements through foreach.
First, use foreach to traverse the Dog collection
12345678910111213141516171819202122 |
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、通过foreach遍历集合显示各条狗狗信息
for
(Object object :dogs){
Dog dog = (Dog) object;
System.out.println(dog.getName() +
"\t" + dog.getStrain());
}
}
} Learn from teacher Wang (iv): Traversing elements with a foreach loop |