package cn.aust.zyw.demo;
import java.util.Iterator;
/**
* Created by zyw on 2016/2/17.
*/
public class BagTest {
public static void main(String args[]){
Bag<Double> bag=new Bag<Double>();
for(int i=0;i<4;i++){
bag.add(i*1.0);
}
int N=bag.size();
double sum=0.0;
/*for(double x:bag){
sum+=x;
}*/
for(Iterator<Double> iter = bag.iterator();iter.hasNext();){
sum=sum+iter.next();
}
double mean=sum/N;
System.out.printf(sum+" ");
System.out.printf(mean+"");
}
}
package cn.aust.zyw.demo;
import java.util.Iterator;
/**
* Created by zyw on 2016/2/17.
*/
public class Bag<T> implements Iterable<T> {
private LinkedList<T> myList;
private int size=0;
Bag(){
myList=new LinkedList<T>();
}
void add(T item){
myList.add(item);
++size;
}
boolean isEmpty(){
return (myList.size==0);
}
int size(){
return size;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>(){
public int i=0,k=0;
@Override
public boolean hasNext() {
if(i<size()){
i++;
return true;
}
return false;
}
@Override
public T next() {
return myList.get(k++);
}
};
}
}
package cn.aust.zyw.demo;
/**
* Created by zyw on 2016/2/17.
*/
public class LinkedList<E> {
public Node<E> header=null;
public Node<E> end=null;
int size=0;
public LinkedList(){
this.header=new Node<E>();
}
/**
* 添加新的节点
* */
public boolean add(E e){
//这里从header就是其中的一个节点
if(size==0){
header.e=e;
end=header;
}else{
Node<E> newnode=new Node<E>(e);
end.addNext(newnode);
end=newnode;
}
size++;
return true;
}
/**
* 根据索引得到该节点的值
* */
public E get(int index){
return getNode(index).e;
}
/**
* 根据index得到该节点
* */
private Node<E> getNode(int index){
if(index<0||index>size-1)//从第0个开始算起
throw new RuntimeException("当前index值错误:"+index);
Node<E> temp=new Node<E>();
temp=header;
int count=0;
while(index!=count){
temp=temp.next;
count++;
}
return temp;
}
/*
* 用来存放数据的节点型内部类
* */
private class Node<e>{
private E e;
Node<E> next=null;
Node(){}
Node(E e){
this.e=e;
}
//可以用这个简化
void addNext(Node<E> node){
this.next=node;
}
}
}