• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generics, Wildcards and Covariant Return

 
Ranch Hand
Posts: 241
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't understand why the code below compiles:

but this doesn't:

Surely, if I'm saying T extends Number, I should be able to return a List<Number>?
 
T Vergilio
Ranch Hand
Posts: 241
5
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Never mind, I can see it now... Number is not a subclass of T, and I need to return T or any subclasses. That was a silly question
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Vergilio, the code won't compile even if you try to return ArrayList<Integer>. The problem is that within the method you can't decide what the type of the returned ArrayList will be. Even if you simplify the return type you won't be able to return ArrayList<Number>

 
T Vergilio
Ranch Hand
Posts: 241
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ankit,

Yeah, that's a bit of a mess and doesn't make much sense on its own (I was trying to test an edge case and may have gone a bit too far there). You're right, the code needs to decide what T is. Something like this would have been better:

So T is whatever is passed in as an argument. I could then call it using:
 
reply
    Bookmark Topic Watch Topic
  • New Topic