定义
- 背包是一种不支持从中删除元素的集合数据类型
- 它的目的就是帮助用例收集元素并迭代遍历所有收集到的元素
- 用例也可以检查背包是否为空或者获取背包中元素的数量
- 迭代的顺序不确定且与用例无关
Java代码实现
import java.util.Iterator;
public class Bag<Item> implements Iterable<Item> {
private Node first;// 链表的首结点
private int N;// 元素数量
public boolean isEmpty() {
return 0 == N;
}
public int size() {
return N;
}
// 和Stack的push()方法完全相同
public void add(Item item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class Node {
Item item;
Node next;
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return null != current;
}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
}
public class Test {
public static void main(String[] args) {
Bag<Double> numbers = new Bag<Double>();
double[] nums = {100, 99, 101, 120, 98, 107, 109, 81, 101, 90};
for (double num : nums) numbers.add(num);
int N = numbers.size();
double sum = 0.0;
for (double x : numbers)
sum += x;
double mean = sum / N;
sum = 0.0;
for (double x : numbers)
sum += (x - mean) * (x - mean);
double std = Math.sqrt(sum / (N - 1));
System.out.printf("Mean: %.2f
", mean);
System.out.printf("Std dev: %.2f
", std);
}
}
Mean: 100.60
Std dev: 10.51