java 集合的几中遍历方式

public static void list1(List li) {
		li.add("张三");
		li.add("李四");
		li.add("王五");
		// 超级for循环遍历
		for (Object attribute : li) {
			System.out.println(attribute);
		}
		
		//for循环下标遍历  暂不写

		// 迭代器
		System.out.println("list3 方法开始!");
		Iterator<Object> it = li.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
	
	public static void map1() {
		Map<Integer,Object> map =new HashMap<Integer, Object>();
		for(int i=0;i<3;i++){
			Student stu =new Student();
			stu.setId(i+2);
			stu.setStuname("student"+i);
			stu.setStuage("17"+i);
			map.put(i, stu);
		}
		
		//遍历map
		//1.增强的for循环(entry集合)
		for(Entry<Integer,Object> entry: map.entrySet()){
			System.out.println(entry.getKey());
			System.out.println(((Student)entry.getValue()).getStuname());
		}
		
		//2.增强的for循环(key集合)
		 for(Integer key:map.keySet()){  
	            System.out.println(key+" = "+map.get(key));  
	        }  		
		//3.遍历值集合
		 for(Object value:map.values()){  
	            System.out.println(((Student)value).getStuage());  
	        } 		
	}
	
	public static void set1() {
		HashSet<String> set=new HashSet<String>();  
        set.add("zhangsan");  
        set.add("lisi");  
        set.add("wangqu");  
        //1.增强的for循环  
        for(String elt:set){  
            System.out.println(elt);  
        }  
        //2.迭代器  
        Iterator<String> it=set.iterator();  
        while (it.hasNext()) {  
            System.out.println(it.next());  
              
        } 
				
		
	}
	
	public static void array1() {
		String [] arr=new String[] {"aa","bb","cc"};  
        //1.增强的for循环  
        for(String elt:arr){  
            System.out.println(elt);  
        }  
        //2.下标的方式  
        for (int i = 0; i < arr.length; i++) {  
            System.out.println(arr[i]);  
        } 
	}


各遍历方式的适用于什么场合?

 

1、传统的for循环遍历,基于计数器的:

        顺序存储:读取性能比较高。适用于遍历顺序存储集合。

        链式存储:时间复杂度太大,不适用于遍历链式存储的集合。

2、迭代器遍历,Iterator:

        顺序存储:如果不是太在意时间,推荐选择此方式,毕竟代码更加简洁,也防止了Off-By-One的问题。

        链式存储:意义就重大了,平均时间复杂度降为O(n),还是挺诱人的,所以推荐此种遍历方式。

3、foreach循环遍历:

        foreach只是让代码更加简洁了,但是他有一些缺点,就是遍历过程中不能操作数据集合(删除等),所以有些场合不使用。而且它本身就是基于Iterator实现的,但是由于类型转换的问题,所以会比直接使用Iterator慢一点,但是还好,时间复杂度都是一样的。所以怎么选择,参考上面两种方式,做一个折中的选择。

4.

一个数据集合实现了该接口,就意味着它支持Random Access,按位置读取元素的平均时间复杂度为O(1)。比如ArrayList。

        而没有实现该接口的,就表示不支持Random Access。比如LinkedList。


if (list instanceof RandomAccess) {
    //使用传统的for循环遍历。
} else {
    //使用Iterator或者foreach。
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值