I am trying to write a simple program for a class called Number
that takes a generic parameter.
my idea here is I would like to store these Number
in List
so that I can traverse through it and find sum.
my list would be of type [2,3.4,4,5]. That is a mixture of int, doubles. my current code is below import java.util.*;
class Number<T> {
T n;
Number(T n) {
this.n=n;
}
public T getnumber(){
return n;
}
public String toString() {
return n.toString();
}
}
public class GenericsWildcards {
public static void main(String[] args) {
Number num1=new Number(5);
Number num2= new Number(5.4);
Number num3=new Number(1.2);
List<Number> list=new ArrayList<Number>();
list.add(num1);
list.add(num2);
list.add(num3);
System.out.println(list);//prints correctly
double sum=0;
for (Number i : list){
sum+=i.getnumber();//compile error here
}
System.out.println("sum is "+ sum);
}
}
The sysout prints correctly the list, but I am unable to getnumber
since it is return of type Object
. I tried casting it to double,sum+=(Double)i.getnumber();
but still did not help.
how can I fix this? any idea for improvement on better implementation is very much appreciated.
Thank you