title: Overcome type erasure in Java
body: <p>I have a client class which I cannot change.</p>
  
  <pre><code>List&lt;Integer&gt; list1= Arrays.asList(1,2,3);
  System.out.println("Total sum is:"+sum(list1));
  printlist(list1);
  List&lt;Double&gt; list2=Arrays.asList(1.0,2.0,3.0);
  System.out.println("Total sum is:"+sum(list2));
  printlist(list2);
  </code></pre>
  
  <p>I have the business logic here</p>
  
  <pre><code>private static Object sum(List&lt;? extends Number&gt; list) {
      double sum = 0;
      for (Number i: list) {
          sum+=i.doubleValue();
      }     
      return sum;
  }
  </code></pre>
  
  <p>So I want to return 6 for integer and 6.0 for a double. How can I do that? I am thinking to typecast sum as int or double based on type but due to type erasure all the info is lost. Can someone help me? </p>