(7)Collection集合的案例(遍历方式 迭代器)
集合的操作步骤:
A:创建集合对象
B:创建元素对象
C:把元素添加到集合
D:遍历集合
a.通过集合对象获取迭代器对象
b.通过迭代器对象的hasNext()判断是否有元素
c.通过迭代器对象的next()方法获取元素并移动到下一个位置
迭代器为什么不定义成一个类,而是一个接口?
假设迭代器定义的是一个类,这样我们就可以创建该类的对象,调用该类的方法来实现集合的遍历。但是呢?我们想想,
java中提供了很多的集合类,而这些集合类的数据结构是不同的,所以,存储方式和遍历的方式应该是不同的。
进而它们的遍历方式应该是不一样的,最终,就没有定义迭代器类的。
而无论你是哪种集合,你都应该具备获取元素的操作,并且,最好在辅助于判断功能,这样,在获取前,先判断。这样就更不容
易出错。也就是说,判断功能和获取功能应该是一个集合遍历所具备的,而每种集合的方式又不太一样,所以我们把这两个功能
给提取出来,并不提供具体实现,这种方式就是接口。
那么,真正的具体的实现类在哪里呢?在真正的具体的子类中,以内部类的方式体现的。
A:存储字符串并遍历
package cn.itcast_04;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
* 需求:存储字符串并遍历。
*
* 分析:
* A:创建集合对象
* B:创建字符串对象
* C:把字符串对象添加到集合中
* D:遍历集合
*/
public class CollectionTest {
public static void main(String[] args) {
// 创建集合对象
Collection c = new ArrayList();
// 创建字符串对象
// 把字符串对象添加到集合中
c.add("林青霞");
c.add("风清扬");
c.add("刘意");
c.add("武鑫");
c.add("刘晓曲");
// 遍历集合
// 通过集合对象获取迭代器对象
Iterator it = c.iterator();
// 通过迭代器对象的hasNext()方法判断有没有元素
while (it.hasNext()) {
// 通过迭代器对象的next()方法获取元素
String s = (String) it.next();
System.out.println(s);
}
}
}
B:存储自定义对象并遍历
package cn.itcast_04;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
* 需求:存储自定义对象并遍历Student(name,age)
*
* 分析:
* A:创建学生类
* B:创建集合对象
* C:创建学生对象
* D:把学生对象添加到集合对象中
* E:遍历集合
*/
public class CollectionTest2 {
public static void main(String[] args) {
// 创建集合对象
Collection c = new ArrayList();
// 创建学生对象
Student s1 = new Student("貂蝉", 25);
Student s2 = new Student("小乔", 16);
Student s3 = new Student("黄月英", 20);
Student s4 = new Student();
s4.setName("大乔");
s4.setAge(26);
// 把学生对象添加到集合对象中
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
c.add(new Student("孙尚香", 18)); // 匿名对象
// 遍历集合
Iterator it = c.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
package cn.itcast_04;
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}