Skip to content

Generics and Variance of Types

bryanwangpengjun edited this page Sep 10, 2020 · 1 revision

Generics

  • Abstraction principle: avoid defining similar methods/classes with duplicate code
  • Allows the specification, with a single method/class declaration, of a set of related methods/classes/types

Autoboxing and Unboxing

  • Primitives types are not the same as classes and so cannot be used with generics
  • Primitives are therefore auto-boxed/unboxed in Java to their corresponding wrapper class

Covariance, contravariance, invariance

Variance Meaning
Covariant preserves the ordering of types
Contravariant reverses the ordering of types
Invariant none of the above

Java Collections Framework (JCF)

  • A collection is an object that represents a group of objects
  • Since these objects can be of any class, we thus use a generic type to avoid defining similar methods/classes with duplicate code (recall abstraction principle)
Clone this wiki locally