java - not correctly casting back from generic type -


i attempting create junit tester check if median method returns double if given double. there seems sort of casting error missing together. appreciated. thank help. edit: required use collection of type number add sequences mixed integers , doubles , ensure when cast back, integers returned integers , doubles returned doubles

the question attempting complete follows: testnumberparsimony: test when mixed integer , double concrete types added statcollection, maintain concrete types integer or double. mode, min, or max should return concrete type integer or double, according types numbers when added statcollection. (hint: can test number's type attempting cast of number retrieved statcollection.)

here median method. given generic type creates collection of type array list out of

 public class statcollection<e extends number> extends java.util.abstractcollection<e> implements statskeeper<e>{ collection c;  public statcollection(){     c=new arraylist<e>(); } public number median(){     if(c.size()<1){//throws exception if attempts method @ size less 1         throw new arithmeticexception();//throws arithmetic acception     }     number retn;//number returned     arraylist<e> n=new arraylist<e>();//create new arraylist     n.addall(c);//copy elements in collection arraylist     number[] numlist= new number[n.size()];//create new array     (int i=0; i<n.size();i++){         numlist[i]=n.get(i);//copy elements arraylist array     }     arrays.sort(numlist);//use arrays sorting function     return (e) numlist[n.size()/2];//return median  } 

here junit tester median, checks whether correctly returns double

private statcollection c=new statcollection<number>(new arraylist<number>()) /*  * testmediandouble  * tests median method double mode value  */ @test public void testmediandouble(){     number[] input={5.0,3.0,2,5.0,10.0,12.0, 5.0, 5.0};//create new list of inputs test whether median returned integer value     collections.addall(c, input);//add new inputs collection     try{         double n=(double)c.median();//attempt cast should integer mode value integer     }     catch(classcastexception ex){         fail();//if cast exception happens fail test, number not of correct type     } } 

when load double , int values number[] input array, lose identity doubles or ints--they autoboxed , stored instances of abstract number class.

thus, there no way guarantee given instance of number in fact double holding reference double, , in fact, array not holding references doubles.

unless there reason use number class, store values raw type double if doubles need.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -