| 有两种办法,一个是普通的for循环,需要把集合转换为字符串数组,然后遍历 private static void demo1() {
 Collection c  = new ArrayList(/*使用ArrayList空参*/);//父类引用指向子类对象,因为Collection是所有集合的根接口,
 //接口不能被实体化,所以可以使用其子类对象,这就是多态,运行看右边,变异看左边
 c.add("hello");//使用子类方法对向集合中添加元素
 c.add("world");
 c.add("java");
 c.add("css");
 c.add("html");
 //Iterator it = c.iterator();
 Object [] arr = c.toArray();//
 for (int i = 0; i < c.size(); i++) {
 if(arr[i].equals("html")){
 System.out.println(arr[i]);
 }
 }
 }
 还有一种就是使用迭代
 package test;
 
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
 
 import com.Student.Student;
 
 public class Demo3 {
 
 /**
 * @param args
 * 自定义对象使用迭代器对集合进行遍历
 * ArrayList是实现Collection接口的子类,接口即可以被实现,实现是多实现,也可以被继承
 */
 public static void main(String[] args) {
 Collection c = new ArrayList();//父类引用指向子类对象
 c.add(new Student("张三",23));//add添加自定义对象,是ArrayList中的方法
 c.add(new Student("赵四",23));
 c.add(new Student("刘能",23));
 c.add(new Student("谢广坤",23));
 c.add(new Student("谢大脚",23));
 Iterator it = c.iterator();//获取迭代器;; 返回在此 collection 的元素上进行迭代的迭代器
 while(it.hasNext()){        //判断集合中是否还有可以迭代的元素,如果有返回true
 Student s = (Student)it.next();//向下转型
 System.out.println(s.getName()+"..."+s.getAge());
 }
 }
 
 }
 
 |