0

why no autoboxing in line sum +=nums[i].doubleValue(). u can see nums[i] is in object form why can't just write sum +=nums[i], why need doubleValue() which is manual way of autoboxing and unboxing. i have successfully compiled a program where number in form of object is returned from the method and automatically assigned as double.

public class genericbound<T extends Number> {
    T[] nums;
    genericbound(T[] o){
          nums=o;
    }
    double average(){
        double sum=0.0;
        for(int i=0; i<nums.length; i++)
            sum +=nums[i].doubleValue();
        return sum/nums.length;
    }
}
    class BoundsDemo{
public static void main(String args[]){
Integer inums[]={1,2,3,4,5};
genericbound<Integer> iob= new genericbound<Integer>(inums);
double v=iob.average();
System.out.println("iob average is"+v);
Double dnums[]={1.1, 2.2, 3.3, 4.4, 5.5 };
genericbound<Double> dob= new genericbound<Double>(dnums);
double w= dob.average();
System.out.println("dob average is "+w);
}
    }
indian0 girl
  • 121
  • 1
  • 8

1 Answers1

0

Autoboxing/Unboxing works with Wrapper classes

Like Double, Integer, Character.

Number is not a wrapper class, so it won't work with Number.

Your method can be modified as below to work with Integers and Doubles both.

double average() {
    double sum = 0.0;
    for (int i = 0; i < nums.length; i++)
        if( nums[i] instanceof Double) {                    
            sum += nums[i].doubleValue();
        } else if(nums[i] instanceof Integer) {
            sum += nums[i].intValue();
        }
    return sum / nums.length;
}
11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • thanks but , i have removed the "extend Number" int the program and tried compiling but still error. where as other similar type of program is there aa aa – indian0 girl Oct 29 '16 at 09:14
  • thanks but , i have removed the "extend Number" int the program and tried compiling but still error. where as other similar type of program, see this line int v=iob.getob(); this program works class Gen T ob; Gen(T o){ ob=o; } T getob(){ return ob; } class GenDemo{ public static void main(String args[]){ Gen iob=new Gen(88); int v= iob.getob(); System.out.println("value "+ v); } } – indian0 girl Oct 29 '16 at 09:21