001package de.hdm_stuttgart.mi.sd1.store; 002 003/** 004 * A container holding a fixed 005 * number of integer values. 006 * 007 */ 008public class IntegerStore { 009 010 final static int defaultCapacity = 4; 011 int[] values ; // Array containing our values 012 int numValues = 0; // Number of values present in the container so far. 013 014 /** 015 * Create a new store being able to 016 * hold integer values. 017 * 018 */ 019 public IntegerStore() { 020 values = new int[defaultCapacity]; 021 } 022 /** 023 * Create a new store being able to 024 * hold integer values. 025 * 026 * @param capacity The store's initial capacity. If more values 027 * are being added via {@link #addValue(int)} the capacity 028 * will be increased dynamically. 029 * 030 */ 031 public IntegerStore(int capacity) { 032 values = new int[capacity]; 033 } 034 035 /** 036 * @return The number of elements the store may 037 * hold, see {@link #IntegerStore(int)}. 038 */ 039 public int getCapacity() { 040 return values.length; 041 } 042 043 /** 044 * @return The number of values being contained. 045 */ 046 public int getNumValues() { 047 return numValues; 048 } 049 050 /** 051 * Insert a new value into our container 052 * 053 * @param value The value to be inserted. This will increment 054 * {@link #getNumValues()} by one. 055 * 056 */ 057 public void addValue(int value) { 058 if (values.length <= numValues) { // Sufficient capacity available to add a new value? 059 final int[] currentArray = values; 060 values = new int[2 * currentArray.length]; // Double the current array's size. 061 for (int i = 0; i < currentArray.length; i++) { 062 values[i] = currentArray[i]; 063 } 064 } 065 values[numValues++] = value; 066 } 067 068 /** 069 * Access the value at a given index 070 * 071 * @param index The desired value's index 072 * @return The desired value. Precondition: index < {@link #getNumValues()}} 073 * 074 */ 075 public int getValue(int index) { 076 return values[index]; 077 } 078 079 /** 080 * Empty the current set of values and set the store 081 * to its initial state. 082 */ 083 public void clear() { 084 numValues = 0; 085 } 086 087 /** 088 * @return The given sample's arithmetic average 089 */ 090 public double getAverage() { 091 double sum = 0; 092 for (int i = 0; i < numValues; i++) { 093 sum += values[i]; 094 } 095 return sum / numValues; 096 } 097}