This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Doubt

 
Lucky J Verma
Ranch Hand
Posts: 278
  • 0
  • 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
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic