using generics to implement a list that takes int and double and return sum in Java -
this question has answer here:
- java generics , adding numbers together 5 answers
i trying write simple program class called number
takes generic parameter. idea here store these number
in list
can traverse through , find sum.
my list of type [2,3.4,4,5]. mixture of int, doubles. current code 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; (number : list){ sum+=i.getnumber();//compile error here } system.out.println("sum "+ sum); } }
the sysout prints correctly list, unable getnumber
since return of type object
. tried casting double,sum+=(double)i.getnumber();
still did not help. how can fix this? idea improvement on better implementation appreciated. thank you
you not need create own number class accomplish this. can use java library class of number accomplish little autoboxing.
public static void main(string[] args) { list<number> list = new arraylist<number>(); list.add(5); list.add(5.4); list.add(1.2); system.out.println(list); double sum = 0; for(number : list){ sum += i.doublevalue(); } system.out.println("sum " + sum); }
i used doublevalue() add numbers together, while maintaining decimal information.
Comments
Post a Comment