Java — Generic Types

Overview

Generic Types in Java are a way to define methods and classes which can handle any type of object you want to pass. These are mostly used in APIs so they are more flexible.

Generic Methods

In order to define a generic method, you need:

  • Type Parameter — This is a diamond operator before the return type of the method, in the declaration. This tells the compiler that this method will be dealing with generic types. These type parameters can be bounded. Bounded type parameters are generic parameter which are more restricted in the objects that can be accepted. An unbounded type parameter would be expressed as

Where as a bounded type parameter could be

This limits the acceptable object types to be any that extend the Collection interface.

There can also be multiple type parameters defined in a single method. In this case, the method would list the type parameters, separated by commas in the method signature.
For example:

This just means that method is dealing with multiple generic types. Each one of these parameters can be bounded.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store