Java 编写简易List容器类并可使用foreach进行遍历

2020-11-24 12:37:57 浏览数 (3)

实现Iterable接口的类可以使用foreach语法进行遍历,下面是简易的模仿ArrayList的容器类实现,适合新手学习参考。

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

import java.util.Iterator;

/**
 * @author aaa
 * @create 2020/11/17 20:30
 * @desc
 **/
public class StringArrayList implements Iterable<String>{

    private String[] stringArray;
    private Integer size;

    public StringArrayList() {
        stringArray = new String[12];
        size = 0;
    }

    private class It implements Iterator<String>{

        private Integer itSize = 0;

        @Override
        public boolean hasNext() {
            return itSize != size;
        }

        @Override
        public String next() {
            return stringArray[itSize  ];
        }
    }

    public void add(String add){
        stringArray[size  ] = add;
    }

    @Override
    public Iterator<String> iterator() {
        return new It();
    }

    public static void main(String[] args) {
        StringArrayList stringArrayList = new StringArrayList();
        stringArrayList.add("1");
        stringArrayList.add("2");
        stringArrayList.add("3");

        for (String s : stringArrayList) {
            System.out.println(s);
        }
        // out => 1 2 3
    }
}

0 人点赞