Java Generics and adding numbers together

前端 未结 7 1849
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 07:58

I would like to generically add numbers in java. I\'m running into difficulty because the Numbers class doesn\'t really support what I want to do. What I\'ve tried so far

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 08:38

    In order to calculate a sum generically, you need to provide two actions:

    • A way to sum zero items
    • A way to sum two items

    In Java, you do it through an interface. Here is a complete example:

    import java.util.*;
    
    interface adder {
        T zero(); // Adding zero items
        T add(T lhs, T rhs); // Adding two items
    }
    
    class CalcSum {
        // This is your method; it takes an adder now
        public T sumValue(List list, adder adder) {
            T total = adder.zero();
            for (T n : list){
                total = adder.add(total, n);
            }
            return total;
        }
    }
    
    public class sum {
        public static void main(String[] args) {
            List list = new ArrayList();
            list.add(1);
            list.add(2);
            list.add(4);
            list.add(8);
            CalcSum calc = new CalcSum();
            // This is how you supply an implementation for integers
            // through an anonymous implementation of an interface:
            Integer total = calc.sumValue(list, new adder() {
                public Integer add(Integer a, Integer b) {
                    return a+b;
                }
                public Integer zero() {
                    return 0;
                }
            });
            System.out.println(total);
        }
    }
    

提交回复
热议问题