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());
            }
    
        }
    }
    
  • 相关阅读:
    修复 Visual Studio Error “No exports were found that match the constraint”
    RabbitMQ Config
    Entity Framework Extended Library
    Navisworks API 简单二次开发 (自定义工具条)
    NavisWorks Api 简单使用与Gantt
    SQL SERVER 竖表变成横表
    SQL SERVER 多数据导入
    Devexpress GridControl.Export
    mongo DB for C#
    Devexress XPO xpPageSelector 使用
  • 原文地址:https://www.cnblogs.com/swifthao/p/12776431.html
Copyright © 2011-2022 走看看