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

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

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

 1 package com.himi.collectionIterator;
 2 
 3 public class Student {
 4     private String name;
 5     private int age;
 6     
 7     
 8     public Student(String name, int age) {
 9         super();
10         this.name = name;
11         this.age = age;
12     }
13     public String getName() {
14         return name;
15     }
16     public void setName(String name) {
17         this.name = name;
18     }
19     public int getAge() {
20         return age;
21     }
22     public void setAge(int age) {
23         this.age = age;
24     }
25     
26 
27 }

(2)CollectionIteratorDemo.java,如下:

 1 package com.himi.collectionIterator;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class CollectionIteratorDemo {
 8 
 9     public static void main(String[] args) {
10         //创建集合对象
11         Collection c = new ArrayList();
12         
13         //创建学生对象
14         Student s1 = new Student("独孤求败", 45);
15         Student s2 = new Student("王重阳", 35);
16         Student s3 = new Student("杨过",25);
17         Student s4 = new Student("郭靖", 45);
18         Student s5 = new Student("张无忌", 24);
19         
20         //集合中添加元素(元素是对象)
21         c.add(s1);
22         c.add(s2);
23         c.add(s3);
24         c.add(s4);
25         c.add(s5);
26         
27         //使用迭代器进行迭代
28         Iterator it = c.iterator();
29         while(it.hasNext()) {//使用while循环进行迭代遍历
30             Student s= (Student)it.next();
31             System.out.println("武林高手 "+s.getName()+"----"+"年龄是:"+s.getAge());
32         }
33 
34     }
35 
36 }

运行效果如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4851518.html