java:集合框架(集合的遍历之迭代器遍历)

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/82955467

 A:迭代器概述
    * 集合是用来存储元素,存储的元素需要查看,那么就需要迭代(遍历) 

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.heima.bean.Student;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Demo5_Iterator {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		demo1();
		demo2();

		}

	public static void demo2() {
		Collection c=new ArrayList();
		c.add(new Student("张三",23));//Object obj=new Student("张三",23);
		c.add(new Student("李四",24));
		c.add(new Student("王五",25));
		c.add(new Student("赵六",26));
		Iterator it=c.iterator();//获取迭代器
		while(it.hasNext()) {
			Student aa=(Student)it.next();//向下转型,使用子类的属性和行为
			System.out.println(aa.getName());
		}
	}

	public static void demo1() {
		Collection c1=new ArrayList();
		c1.add("a");
		c1.add("b");
		c1.add("c");
		c1.add("d");
		//对集合中的元素进行迭代(遍历)
		Iterator it=c1.iterator();//获取迭代器
//		boolean b1=it.hasNext();//判断集合中是否有元素,有就返回true
//		Object obj1=it.next(); 
//		System.out.println(b1);
//		System.out.println(obj1);
//		
//		
//		boolean b2=it.hasNext();//判断集合中是否有元素,有就返回true
//		Object obj2=it.next(); 
//		System.out.println(b2);
//		System.out.println(obj2);
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24644517/article/details/82955467
今日推荐