Last active
October 1, 2015 19:57
-
-
Save vpiotr/c586f5e010a8c040980b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: