Collections with Generics

Quick Reference

  • Polymorphism is applicable only for base type but not for type parameter
  • Primitive cannot be passed as type parameter only object reference is allowed

Which of them works ?

  • ArrayList<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type ArrayList
  • List<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type List
  • Collection<String> l = new ArrayList<String>();
    • Valid-Polymorphism on Base Type Collection
  • ArrayList<Object> l = new ArrayList<String>();
    • Invalid-Polymorphism on parameter type
    • (Compile Time Error : Incompactable Types found ArrayList<String> required ArrayList<Object>)

Conclusion 1: Usage of parent reference to hold child object is the concept of polymorphism but it does not apply for type parameter

  • ArrayList<int> l = new ArrayList<int>();
    • Compile Time Error : Unexpected type found int required reference.

Conclusion 2 : For Type parameter we can provide any class or interface name but not primitives.

Leave a Comment