zoukankan      html  css  js  c++  java
  • Java基础--Stack,Queue和Map的遍历

    总结

    集合元素的遍历,最好使用foreach()

    Stack的遍历

    public class TestStack {
        public static void main(String[] args) {
            Stack<Integer> s = new Stack<Integer>();
            for (int i = 0; i < 10; i++) {
                s.push(i);
            }
    
            //集合遍历方式
            for (Integer x : s) {
                System.out.println(x);//输出0-9,这个顺序是压入的顺序
            }
            System.out.println("-----------");
    
            //栈弹出遍历方式
    //      while (s.peek()!=null) {    //不健壮的判断方式,容易抛异常,正确写法是下面的
            while (!s.empty()) {
                System.out.println(s.pop());//输出9-0,从栈顶到栈底
            }
        }
    }
    

    Queue的遍历

    public class TestQueue {
        public static void main(String[] args) {
            Queue<Integer> q = new LinkedBlockingQueue<Integer>();
            //初始化队列
            for (int i = 0; i < 5; i++) {
                q.offer(i);
            }
    
            //集合方式遍历,元素不会被移除
            for (Integer x : q) {
                System.out.println(x);//输出0-4
            }
            System.out.println("------------");
            //队列方式遍历,元素逐个被移除
            while (q.peek() != null) {
                System.out.println(q.poll());//输出0-4
            }
        }
    }
    

    Map的遍历

    public class TestMap {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("1", "a");
            map.put("2", "b");
            map.put("3", "c");
    
            //最简洁、最通用的遍历方式
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
    
        }
    }
    
  • 相关阅读:
    ASP.NET 中Request.QueryString 中的key
    我要爱死这个markdown 了
    WindowsPhone 8 开发 之 本地数据库应用
    java对象详解
    java内存分析
    java 成长之路
    springboot hessian
    zabbix 3.0 安装 ubuntu环境
    dubbo+zookeeper简单环境搭建
    大型网站及架构演进过程
  • 原文地址:https://www.cnblogs.com/swifthao/p/12776431.html
Copyright © 2011-2022 走看看