日期:2014-05-20 浏览次数:20680 次
package ex11_01; /**This is a generic container class to store a list of objects * * @author WangDong *@version 19th December 2011 */ public class ObjectList { private Object[] list; //之前并未写过Object类,后面别的类继承竟然可以直接用 private int total; /**Constructor intitialises an empty list * @param sizeIn Used to set the maximum size of the list */ public ObjectList(int sizeIn){ list=new Object[sizeIn]; total=0; } /**Add an object to the end of the list * @param objectIn The object to add * @return Returns true if the object was added successfuly * add false otherwise */ public boolean add(Object objectIn){ if(!isFull()){ list[total]=objectIn; total++; return true; } else{ return false; } } /**Reports on whether or not the list is empty * @return Returns true if the list is empty * and false otherwise */ public boolean isEmpty(){ if(total==0){ return true; } else{ return false; } } /**Reports on whether or not the list is full * @return Returns true if the list is full * and false otherwise */ public boolean isFull(){ if(total==list.length){ return true; } else{ return false; } } /**Reads an object from a specified position in the list * @param i The position of the object in the list * @return Returns the object at the specified position in the list * or null if no object is at at that position */ public Object getItem(int positionIn){ if(positionIn<1||positionIn>total){ return null; } else{ return list[positionIn-1]; } } /**Reads the number of objects stored in the list*/ public int getTotal(){ return total; } /**Remove an object from the specified position in the list * @param numberIn The position of the object to be removed * @return Returns true of the item is removed successfully * and false otherwise */ public boolean remove(int numberIn){ if(numberIn>=1&&numberIn<=total){ for(int i=numberIn-1;i<=total-2;i++){ list[i]=list[i+1]; } total--; return true; } else{ return false; } } }
package ex11_01; /**Collection class to hold a list of Payment objects * * @author WangDong *@version 19th December 2011 */ public class PaymentList extends ObjectList{ /**Constructor initialises the empty list and sets the maximum list size */ public PaymentList(int sizeIn){ super(sizeIn); //Call ObjectList constructor } /**Reads the payment at the given position in the list * @param positionIn The position of the payment in the list * @return Returns the payment at the position */ public Payment getPayment(int positionIn){ if(positionIn<1||positionIn>getTotal()){ //No object found at given position return null; } else{ //Call inherited method and type cast return (Payment)super.getItem(positionIn); //这里直接强制转换一下就可以吗 } } /**Returns the total value of payments recorded*/ public double calculateTotalPaid(){ double totalPaid=0;//Intialize total paid //Loop throuth all payments for(int i=1;i<=super.getTotal();i++){ totalPaid+=getPayment(i).getAmount(); } return totalPaid; } }