Subtype in Generics?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    Subtype in Generics?

    Code:
    List<Number> li1 = ..;
    List<Integer> li2 = ..;
    li1 = li2; //[B]li1[/B] can't be subtype of [B]li2[/B]
    Explain: If li1 gets updated with the Sub Class of Number and which is not integer then accessing li2 results runtime error.

    Then ..
    Code:
    List<?> li1 = ..;
    li1 = li2; //it's valid
    Here you can't update li1 except null.

    Code:
    List<? extends Number> li1 = ..;
    li1=li2; //it's also valid
    Here you can't also update li1 except null for the same reason(explaine d earlier).

    So with the valid codes li1 can't be updated. Then why ? extends SuperClass. What's the problem with first code fragment?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Read (especially) Chapter 3 from this link.

    kind regards,

    Jos

    Comment

    Working...