开发者

Simple Java Overriding Methods

开发者 https://www.devze.com 2023-02-11 07:09 出处:网络
I was wondering if it is possible to override Java methods in a simpler way. My basic problem is that I have a collection of methods, an example can be calculating the mean of an array of values. My p

I was wondering if it is possible to override Java methods in a simpler way. My basic problem is that I have a collection of methods, an example can be calculating the mean of an array of values. My problem is that I want to have this method work for all number variables types (int long double float etc.) Is there any way to do th开发者_如何学JAVAis besides creating:

  1. A new method for each parameter type
  2. Having those new methods call one base method with parsed parameters

Any help is appreciated.

When reviewing the answer, I noticed that I have been using generics, I just didn't know what they were called. Here is an example of my mean snippet.

   public double arithmeticMean(List<Double> data) {

        double sum = 0;
        for (double number : data)
            sum += number;
        return sum / data.size();
    }

I was wondering if there was anyway to generalize this to other number variables (besides the forms listed above.)


Have you investigated using generics and define a new calculator object for Double, Float, Integer etc. ?


As Brian said, generics would be the best way to do this. To do the mean of a LinkedList (not sure if there's a way to do this with arrays or not):

public double mean(LinkedList<? extends Number> numbers) {
  double sum = 0.0;
  for(Number n : numbers) sum += n.doubleValue();
  return sum / (double)numbers.size();
}


You can write something like that:

public static <T extends Number> BigDecimal getMean(final List<T> numbers) {
    BigDecimal sum = BigDecimal.ZERO;

    for (T t : numbers) {
        sum = sum.add(new BigDecimal(t.doubleValue()));
    }

    return sum.divide(new BigDecimal(numbers.size()));
}

The usage would be:

List<Double> list = new ArrayList<Double>();
list.add(1d);
list.add(5d);
System.out.println(getMean(list)); // 3
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号