Generics in Java

  • Generics Overview
  • Generic Methods
  • Bounds
  • Wildcards

Generics Overview

List list = new ArrayList();
List<String> list = new ArrayList<>();
  • We can see that it allowed StringBuilder to get into our list. Because its list of Object and StringBuilder is a child of the object so it’s totally fine for a compiler.
  • And during runtime when we get back items from the list trying to convert to String, we get our exception.
  • We are getting compiler errors when we try to add StringBuilder to our list. The error during compilation is always better than during runtime.
  • Bucket<E> we mention in the declaration of the class that we use generics and then inside our class we can use it as we have this type.
  • The actual type of <E> will be assigned by the client code.
  • In the main method take a look how our Bucket class can take String and then Integer.
  • <E, S, T> that’s how we use multiple generics type parameters.
  • Interfaces can utilize generics as well.

Generic Methods

  • <E, S> booleanWe need to specify type parameters before method return type and then we can use them as method arguments
    isSame(E element, S secondElement)


  • We use extends to specify outbounds. Every class, including the bound class itself, that extends/implements our bound class can be used as a type argument for generics.
Garage g = new Garage();
g.putInside(new BMW());
Audi audi = (Audi)g.getOut(); // runtime exception
// ------Garage<Audi> g1 = new Garage<>();
g1.putInside(new BMW()); // does not compile here


  • Integer and Double both extend Number so we can pass a list of them safely in our method.
  • Upper bounded let us use an unknown type(?) or a subtype of it.
Audi -> Car -> Object
public static void printList(List<? super Audi> list) {
// code here..
  • printList method now can accept List<Audi>, List<Car>, List<Object>
public static void printList(List<Object> list) {
for (Object el : list) {
public static void printList(List<?> list) {
for (Object el : list) {
  • Now we can pass List with any type




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