aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Doubt" Watch "Generics Doubt" New topic
Author

Generics Doubt

Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
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

Joined: Jun 04, 2007
Posts: 377
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics Doubt