Java基础知识强化之集合框架笔记08:Collection集合自定义对象并遍历案例(使用迭代器)

1. Collection集合自定义对象并遍历案例(使用迭代器)

(1)首先定义一个Student.java,如下:

 package com.himi.collectionIterator;

 public class Student {
private String name;
private int age; 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;
} }

(2)CollectionIteratorDemo.java,如下:

 package com.himi.collectionIterator;

 import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; public class CollectionIteratorDemo { public static void main(String[] args) {
//创建集合对象
Collection c = new ArrayList(); //创建学生对象
Student s1 = new Student("独孤求败", 45);
Student s2 = new Student("王重阳", 35);
Student s3 = new Student("杨过",25);
Student s4 = new Student("郭靖", 45);
Student s5 = new Student("张无忌", 24); //集合中添加元素(元素是对象)
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
c.add(s5); //使用迭代器进行迭代
Iterator it = c.iterator();
while(it.hasNext()) {//使用while循环进行迭代遍历
Student s= (Student)it.next();
System.out.println("武林高手 "+s.getName()+"----"+"年龄是:"+s.getAge());
} } }

运行效果如下:

Java基础知识强化之集合框架笔记08:Collection集合自定义对象并遍历案例(使用迭代器)

上一篇:React-Native WebView动态加载字体


下一篇:关于css样式加载的问题