Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Doubt

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a program , based on generics.
here, When i sed Enhanced loop,it doenst work.
Why its not working .Is it like enhanced dont work with generics,

public class AverageCalGenerics<T extends Number > {
T[]nums;
AverageCalGenerics(T[]n){nums=n;}
double calcAverage(){
double sum=0.0;
//for(T i:nums){sum=sum+i;} //Enhanced for loo-NOT WORKING
for(int i=0;i<nums.length;i++)
{
//sum=sum +nums[i];
sum+=nums[i].doubleValue();

}
return (sum/nums.length);
}

public static void main(String args[]){

Integer arr[]={1,2,3,4};
AverageCalGenerics avg=new AverageCalGenerics(arr);
System.out.println(avg.calcAverage());
}
 
Manfred Klug
Ranch Hand
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lucky,

the enhanced for loop works as expected. But you should think about the type 'i' has at runtime. Then you know why 'sum=sum+i' fails.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic