-2

I am trying to compile the below code but getting "incompatible types object cannot be converted to Number at for(Number n:list).

import java.util.*;

 class Output
  {
    public static double sumOfList(List list)
    {
        double s=0.0;

        for(Number n:list)
            s+=n.doubleValue();

        return s;
    }

    public static void main(String[] args) 
    {
        List li=Arrays.asList(1,2,3);
        System.out.println(SumOfList(li));
    }
  }
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Shaikh Nadeem
  • 29
  • 3
  • 10
  • 1
    @SotiriosDelimanolis I really don't think this counts as a duplicate of that question. This question is simple enough there is probably some duplicate out there, but the one above... – Matt Ball Jan 17 '15 at 20:09

2 Answers2

4

Listen to the "Raw types" warning your compiler outputs and use generics.

Declare the list type as List<Number> or List<? extends Number>.

http://ideone.com/L6mIhA

(and never use raw types. They only exist for backwards compatibility.)

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

chage your code to this:

public static double sumOfList(List<Number> list){
..
}
roeygol
  • 4,908
  • 9
  • 51
  • 88