java - Sum of ArrayList for different types -


is possible write single method total sum of elements of arraylist, of type <integer> or <long>?

i cannot write

public long total(arraylist<integer> list)  

and

public long total(arraylist<long> list)  

together there error of erasure, , integer not automatically extends long , vice versa... code inside identical!

yes, can implement such method, since both integer , long extend number. example can use wildcard type list element type:

public static long total(list<? extends number> list) {     long sum = 0;     (number n : list) {         sum += n.longvalue();     }     return sum; } 

this works integral types however, since sum variable , return value of type long.

ideally able use method floats , doubles , return object of same type list element type, not easy 2 reasons:

  1. the thing can number value 1 of primitive number types. can not sum 2 of them in number dependent way.
  2. it not possible create 0-object of right class.

edit: much later...

just fun, lets in nice way java. thing have manually provide 2 operations mentioned above. kind of value 2 such operation called monoid in context of algebra , functional programming.

the problem can solved creating objects represent monoid operations:

interface monoidops<t> {     t id();     t op(t o1, t o2); } 

the total method can implemented take object of type in addition list:

public static <t> t total(list<t> list, monoidops<t> ops) {     t sum = ops.id();     (t e : list) {         sum = ops.op(e, sum);     }     return sum; } 

to provide monoidops implementations numeric classes, lets create simple helper class:

class simplemonoidops<t> implements monoidops<t> {     private final t idelem;     private final binaryoperator<t> operation;      public simplemonoidops(t idelem, binaryoperator<t> operation) {         this.idelem = idelem;         this.operation = operation;     }      public t id() {         return idelem;     }      public t op(t o1, t o2) {         return operation.apply(o1, o2);     } } 

the monoidops implementations can written neatly this:

static final monoidops<integer> int_monoid_ops = new simplemonoidops<>(0, integer::sum); static final monoidops<double> double_monoid_ops = new simplemonoidops<>(0.0, double::sum); 

and total method called this:

int sum = total(arrays.aslist(1, 2, 3), int_monoid_ops); 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -