Bag类型

背包是一种不支持从中删除元素的集合数据类型---其作用就是帮助用例收集元素并迭代遍历所有收集到的元素。迭代的顺序不确定且与用例无关。

基于链表

import java.util.Iterator;
import java.util.NoSuchElementException;
public class Bag implements Iterable {
   // 链表
    private static  class Node{
        private Item item;
        private Nodenext;
    }
    private Nodefirst;
    private int n;
    public Bag() {
        first = null;
        n = 0;
    }
    public boolean isEmpty(){
        return first == null;
    }
    public int size(){
        return n;
    }
    private void add(Item item){
        Nodeoldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        n++;
    }
    @Override
    public Iterator iterator() {
        return new ListIterator(first);
    }
    private class  ListIterator implements Iterator{
        private Node current;

        public ListIterator(Node first) {
            this.current = first;
        }

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

        @Override
        public Item next() {
            if (!hasNext())throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}


调用

 public static void main(String[] args){
        Bag numbers = new Bag<>();
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < 10; i++) {
            int a = random.nextInt(100);
            System.out.println(a);
            numbers.add((double) a);
        }
        int N = numbers.size();
        double sum = 0.0;
        for (double x:numbers) {
            sum += x;
        }
        System.out.print(sum);

    }

你可能感兴趣的:(Bag类型)