【Java】Collection遍历使用Iterable迭代器

2021-12-06 13:28:23 浏览数 (2)

代码语言:javascript复制
package com.example.demo.test;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @Author bennyrhys
 * @Date 9/1/21 11:48 PM
 * Iterable随机数生成器
 */
public class RandomString<T> implements Iterable{


    private final List<T> list;

    public RandomString(List<T> list) {
        this.list = list;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator iterator() {
        return new Iterator() {
            @Override
            public boolean hasNext() {
                return true;
            }

            @Override
            public Object next() {
                return list.get((int) (list.size() * Math.random()));
            }
        };
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "b", "c");
        RandomString<String> randomString = new RandomString<>(list);

//        for (Object o : randomString) {
//            System.out.println(o);
//        }

        Iterator iterator = randomString.iterator();
        for (int i = 0; i < 10; i  ) {
            System.out.println(iterator.next());
        }
    }
}

a b c a b c a c a c

Process finished with exit code 0

0 人点赞