Skip to content

Instantly share code, notes, and snippets.

@vpiotr
Last active October 1, 2015 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpiotr/c586f5e010a8c040980b to your computer and use it in GitHub Desktop.
Save vpiotr/c586f5e010a8c040980b to your computer and use it in GitHub Desktop.
/*
* Author: Piotr Likus, SpaceInSoft, 2015
* License: MIT
*/
package com.spaceinsoft.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Generic number accumulator class.
* Calculates sum of values, can be used with any built-in numeric type.
*
* @author Piotr Likus
*/
public class Accumulator<T extends Number> {
private T value;
public Accumulator(T initValue) {
value = initValue;
}
public void add(T aValue) {
this.value = (T) NumberOperatorUtils.add(value, aValue);
}
public void addAll(List<T> list) {
for (T item : list) {
this.value = (T) NumberOperatorUtils.add(value, item);
}
}
public T get() {
return this.value;
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 3, 5);
Accumulator<Integer> acc = new Accumulator<>(0);
acc.addAll(list);
acc.add(5);
assert acc.get() == 14;
System.out.println("Sum of integers: " + acc.get().toString());
List<Double> dblList = Arrays.asList(1.7, 3.0, 5.1);
Accumulator<Double> dblAcc = new Accumulator<>(0.0);
dblAcc.addAll(dblList);
dblAcc.add(3.3);
System.out.println("Sum of doubles: " + dblAcc.get().toString());
}
}
@vpiotr
Copy link
Author

vpiotr commented Oct 1, 2015

Output:

Sum of integers: 14
Sum of doubles: 13.100000000000001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment