Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Generics Doubt

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 > {
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];

return (sum/nums.length);

public static void main(String args[]){

Integer arr[]={1,2,3,4};
AverageCalGenerics avg=new AverageCalGenerics(arr);
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.
    Bookmark Topic Watch Topic
  • New Topic