package com.matao.fundamentals;

import java.util.Iterator;

/**
 * Created by matao on 5/27/16.
 * <p>
 * 背包是一种不支持从中删除元素的集合数据类型
 * 它的目的就是用来收集元素并迭代遍历所有元素,
 * 迭代的顺序不确定
 */
public class Bag<T> implements Iterable<T> {
    private class Node {
        T item;
        Node next;
    }

    private Node head;
    private int size;

    public void add(T item) {
        Node node = new Node();
        node.item = item;
        if (head == null) {
            head = node;
        } else {
            node.next = head;
            head = node;
        }
        size++;
    }

    public int getSize() {
        return size;
    }

    @Override
    public Iterator<T> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<T> {

        private Node current = head;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public T next() {
            T item = current.item;
            current = current.next;
            return item;
        }

        @Override
        public void remove() {

        }
    }

    public static void main(String[] args) {
        Bag<Integer> bag = new Bag<>();
        bag.add(101);
        bag.add(22);
        bag.add(90);
        for (Integer integer : bag) {
            System.out.println(integer);
        }
        System.out.println(bag.getSize());
    }
}

@@ -104,67 +104,349 @@
 %0A * 
-%E8%83%8C%E5%8C%85%E6%98%AF%E4%B8%80%E7%A7%8D%E4%B8%8D%E6%94%AF%E6%8C%81%E4%BB%8E%E4%B8%AD%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0%E7%9A%84%E9%9B%86%E5%90%88%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%0A * %E5%AE%83%E7%9A%84%E7%9B%AE%E7%9A%84%E5%B0%B1%E6%98%AF%E7%94%A8%E6%9D%A5%E6%94%B6%E9%9B%86%E5%85%83%E7%B4%A0%E5%B9%B6%E8%BF%AD%E4%BB%A3%E9%81%8D%E5%8E%86%E6%89%80%E6%9C%89%E5%85%83%E7%B4%A0,%0A * %E8%BF%AD%E4%BB%A3%E7%9A%84%E9%A1%BA%E5%BA%8F%E4%B8%8D%E7%A1%AE%E5%AE%9A
+A bag is a collection where removing items is not supported.%0A * Its purpose is to provide clients with the ability to collect items%0A * and then to iterate through the collected items%0A * (the client can also test if a bag is empty and find its number of items).%0A * The order of iteration is unspecified and should be immaterial to the client.
 %0A */

revise comments