目录
一:利用数组遍历
1:分析
(1、创建学生类
(2、创建学生对象集合
(3、创建学生对象
(4、将学生对象添加到集合中
(5、将集合转成数组
(6、遍历数组(要是想取到对象的成员变量要向下转型)
2:实现
(1:学生类
package protice4;
public class Student {
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
(2:数组遍历
package protice4;
import java.util.ArrayList;
import java.util.Collection;
public class Test13 {
public static void main(String[] args) {
Collection c = new ArrayList();//创建集合对象
//创建三个学生对象
Student s1 = new Student(18, "小花");
Student s2 = new Student(17, "小华");
Student s3 = new Student(18, "小亮");
//将三个学生对象添加到集合中
c.add(s1);
c.add(s2);
c.add(s3);
System.out.println(c);//输出集合
Object[] objects = c.toArray();//将集合转成数组
//遍历数组,将数组中元素向下转型为Student然后输出学生姓名和年龄
for(int i=0;i< objects.length;i++){
Student s = (Student) objects[i];//向下转型
System.out.println(s.getName()+"**"+s.getAge());
}
}
}
二:利用迭代器遍历
1:分析
(1、创建学生类
(2、创建学生对象集合
(3、创建5个学生对象
(4、将5个学生对象加入到集合中
(5、获取迭代器对象
(6、遍历迭代器
2:实现
(1:创建学生类(和上面一样不写了)
(2:迭代器遍历
迭代器遍历需要的方法
boolean hasNext()
如果迭代具有更多元素,则返回 true 。
Object next()
返回迭代中的下一个元素boolean hasNext() 如果迭代具有更多元素,则返回 true 。
迭代器遍历时用while循环
package protice4;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test14 {
public static void main(String[] args) {
Collection c = new ArrayList();//创建集合对象
//创建三个学生对象
Student s1 = new Student(20, "小雨");
Student s2 = new Student(19, "小可");
Student s3 = new Student(18, "小明");
//将三个学生对象添加到集合中
c.add(s1);
c.add(s2);
c.add(s3);
System.out.println(c);//输出集合
Iterator iterator = c.iterator();//获取迭代器
while(iterator.hasNext())//如果下一个不为空
{
Object next = iterator.next();//获取下一个元素
Student s = (Student)next;//向下转型
System.out.println(s.getName()+"**"+s.getAge());//获取姓名和年龄
}
}
}