I've written a class for a project of mine whose responsibility is to perform basic statistic calculations like mean, median and mode. The aim is for it to be a helper class, so it should not be instantiable. I later want to extend it to include weighted mean and range/interquartile range as well as variance.
Here is the code:
import java.util.Arrays;
import java.util.HashMap;
public class BasicStatistics {
//Prevent instantiation...
//throws UnsupportedOperationException to defend against reflection
private BasicStatistics() throws UnsupportedOperationException{
throw new UnsupportedOperationException();
}
public static class Mode {
private static int mode;
private static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
private Mode() throws UnsupportedOperationException{
throw new UnsupportedOperationException();
}
public static int calculateMode(int ints[]){
int max = 0;
int temp = 0;
for (int i = 0; i < ints.length; i++){
if (hm.get(ints[i]) != null){
int count = hm.get(ints[i]);
count += 1;
hm.put(ints[i], count);
if (count > max){
max = count;
temp = ints[i];
}
} else {
hm.put(ints[i], 1);
}
}
if (temp == 0){
mode = ints[0];
} else {
mode = temp;
}
return mode;
}
}
public static class Mean {
private static float mean;
private Mean() throws UnsupportedOperationException{
throw new UnsupportedOperationException();
}
public static float calculateMean(int ints[]){
for (int element : ints){
mean += element;
}
return mean / ints.length;
}
}
public static class Median {
private static float median;
private Median() throws UnsupportedOperationException{
throw new UnsupportedOperationException();
}
public static float calculateMedian(int ints[]){
Arrays.sort(ints);
if (ints.length % 2 == 0){
median = (float) (ints[ints.length / 2] + ints[(ints.length / 2) - 1]);
median /= 2;
} else {
median = (float) ints[ints.length / 2];
}
return median;
}
}
}