Senior developers know how to write utility methods using Java Generics Wildcards, but do you?

Manoj Chemate
Level Up Coding
Published in
3 min readSep 3, 2022

--

Generics have been introduced in Java 5:

  1. To detect bugs at compile time
  2. To help to create generic functions
  3. To eliminate the need for type-casting while reading elements from the collection.

In this article, we will see how to use wildcards (?) to write generic utility methods.

Summary of variants of wildcards :

Assume any Java class A.

  1. Upper Bounded Wildcard ( ? extends A ): can be understood as any class which is A or subclass of A
  2. Lower Bounded Wildcard ( ? super A ): can be understood as any class which is A or super class of A
  3. Unbounded Wildcard ( ? ) : unknown type

1. Upper Bounded Wildcard :

Representation: <? extends A>

Usage: This wildcard can be interpreted as ‘any class which is A itself or subclass of A

Useful when defined as method argument where method implementation only reads data from collection.

Example: Consider the below method which just prints the type of animals

You can pass any list of animals to the above method which extends the Animal class

But:

You can not add objects except null to upper bounded collection.

2. Lower Bounded Wildcard :

Representation : <? super A>

Usage: This wildcard can be interpreted as ‘any class which is A itself or super class of A

Useful when defined as method argument where method implementation only writes data to collection.

Example: Consider the below method which just inserts numbers into the provided list. It can accept either list of Integer or its super classes like Number or Object.

The above method can be used as a utility to add 1 to 10 integers to an integer list or number list or object list. It is important to note that you can only add Integer types to all these lists.

But :

You can add only specified type of object and null to lower bounded collection.

3. Unbounded Wildcard :

Representation : <? >

Usage: This wildcard can be interpreted as ‘unknown class type’ or more informally ‘any type’

Use it as method argument when your method implementation does not want to know what type of objects are present in collection. It means you are just using object class methods or collections generic methods like clear(), size() and toString().

Example: Consider the below method which just validates the size of collections and throws errors.

The above method can be used as a utility to validate the size of any type of list as shown in the code below.

But :

You can not add or read elements from unbounded collection except null.

--

--

Software Engineer, I write about my experience with Java, Spring, Micro-services, gRPC, REST, Data Structures, Algorithms, and Software Engineering Interviews.