0

Hi All,

I am just learning Java and there is a concept that I cannot grasp. I am writing a simple exercise program that works with stacks. I have a sum method for two different types - Integer and Double. They both have the same logic, so it seems redundant to do it this way. I thought it would be possible to write one method that takes either type. So I have read about generics and still cannot figure out a solution. Is it at all possible?

Here are my add methods:

```
// Return the sum of the stack
public static Integer sum (Stack<Integer> stack) {
Integer sum = 0, current;
Stack<Integer> temp = new Stack<Integer>();
// calculate the sum
while (!stack.empty() ) {
current = stack.pop();
sum = sum + current;
temp.push(current);
}
// rebuild the stack
while (!temp.empty()) {
stack.push(temp.pop());
}
return sum;
}
// Return the sum of the stack
public static Double sum (Stack<Double> stack) {
Double sum = 0.0, current;
Stack<Double> temp = new Stack<Double>();
// calculate the sum
while (!stack.empty() ) {
current = stack.pop();
sum = sum + current;
temp.push(current);
}
// rebuild the stack
while (!temp.empty()) {
stack.push(temp.pop());
}
return sum;
}
```