• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Immutability in Upperbound generic wildcard

 
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Page #120 (1Z0-809)



The authors write


List<? extends Bird> could be List<Bird> or List<Sparrow>. Line #7 doesn't compile because we can't add a Sparrow to List<Bird>



The above underlined is factually incorrect. Sparrow can be added to List<Bird>. Or atleast it is not convincingly explained why compilation fails. Could some help me understand why Line #6 not compile?

 
Marshal
Posts: 73994
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you been through the Java™ Tutorials?

Right, a List<Sparrow> is a subtype of List<? extends Bird> but it isn't a subtype of List<Bird>. That means you could assign things like this:-If you had the List you showed in your second code block, you could get Sparrows out of it, but one of its elements isn't a Sparrow. Goodbye type‑safety. Remember that writing <...> instructs the compiler to go into fusspot mode and warn you about every tiny possible doubt and refuse to compile all sorts of things so as to maintain type‑safety. So you can only add one thing to a List<? extends Anything> and that is the one thing you can safely cast to any type: null.
 
Keerthi P
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think I was able explain this myself.

Consider the following code:


 
Campbell Ritchie
Marshal
Posts: 73994
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well done
 
crispy bacon. crispy tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic