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());
        }

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM