zoukankan      html  css  js  c++  java
  • foreach与Iterable学习

    以前对于foreach的使用都是自然而然的感觉,没有深究过为什么可以用,什么时候可以用。最近才发现,原来那些可以使用的类,都是实现了Iterable接口的,否则根本就不能用。

    下面是我之前学习时候写的代码

    package com.test.basic;
    
    import java.util.Iterator;
    
    public class MyMap implements Iterable<Integer>{
    
        private int count;
        public MyMap(int i) {
            this.count=i;
        }
        public Iterator<Integer> iterator() {
            return new Iterator<Integer>() {
                
                public Integer next() {
                    count --;
                    return count;
                }
                
                public boolean hasNext() {
                    // TODO Auto-generated method stub
                    return count > 0;
                }
            };
        }
        public static void main(String[] args) {
            for (int i : new MyMap(10)) {
                System.out.println(i + " ");
            }
        }
    }
  • 相关阅读:
    4-11
    4-10
    4-9
    4-7
    4-8
    4-6
    4-4
    4-5
    4-3
    4-2
  • 原文地址:https://www.cnblogs.com/heben/p/5387548.html
Copyright © 2011-2022 走看看