• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method which adds the contents of ArrayList  RSS feed

 
Carl John
Ranch Hand
Posts: 47
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All ,

I want to write a method which adds the contents of List and returns the sum value.

The below method only accepts List<Integer> and returns int ...



But how can we make this method to accept any list of numbers like Integer,Float,Double to return the sum of List contents..


Thanks in advance
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The classes Integer, Float and Double all extend the class Number. So, you can change your method to accept a List<? extends Number>.

However, what do you want the return type to be? There's no way have it return int when the list is a list of Integers, and double when the list is a list of Doubles. If you want that, you should make several overloaded versions of the method, instead of writing one generic method.

The current method implementation has some flaws. Why are you not using generics on the Iterator, and why are you converting the integer to a string and back in line 5? That's unnecessary. Just write this:

Beyond that, you could have made it a lot simpler, you don't even need an explicit Iterator at all:

 
Carl John
Ranch Hand
Posts: 47
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the answer.It was helpful. Actually i just had an interview yesterday, the interviewer asked to write down a generic method to return sum of contents in list having only digits..
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!