ArrayBag

賈小強
转载请注明原创出处,谢谢!

package com.lab1.test1;

import java.util.Iterator;

public class ArrayBag implements Iterable {
    private int n;
    @SuppressWarnings("unchecked")
    private Item[] a = (Item[]) new Object[2];

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

    private class ListIterator implements Iterator {
        int i = 0;

        @Override
        public boolean hasNext() {
            return i < n;
        }

        @Override
        public Item next() {
            Item item = a[i];
            i++;
            return item;
        }

    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (Item item : this) {
            builder.append(item + " ");
        }
        return builder.toString();
    }

    private boolean isEmpty() {
        return n == 0;
    }

    private int size() {
        return n;
    }

    private void add(Item item) {
        if (n == a.length) {
            resize(a.length * 2);
        }
        a[n++] = item;
    }

    @SuppressWarnings("unchecked")
    private void resize(int capacity) {
        Item[] temp = (Item[]) new Object[capacity];
        for (int i = 0; i < n; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    public static void main(String[] args) {
        ArrayBag bag = new ArrayBag<>();
        System.out.println(bag);
        System.out.println(bag.size());
        System.out.println(bag.isEmpty());

        bag.add("bill");
        bag.add("jack");
        bag.add("lucy");
        System.out.println(bag);
        System.out.println(bag.size());
        System.out.println(bag.isEmpty());
    }

}

输出


0
true
bill jack lucy 
3
false

Happy learning !!

你可能感兴趣的:(ArrayBag)