01. Introduction to Generics

What are generics?

Generics allow an object or method to operate on various types. In other words, they allow for the same code to be run regardless of the type. For example, a linked list that stores data can use Java generics to hold elements of a String, Integer, or Double, all using the same code.

Why Generics?

There are three main reasons we use Java generics.

1) Less code, more functionality

We can re-use the same code with different parameters types.

LinkedList<Integer> intList = new LinkedList<>();
LinkedList<String> stringList = new LinkedList<>();

2) Safe code

Generics allow for safer code, as the compiler now knows which types to check for.

Before we had to cast each type.

LinkedList intList = new LinkedList();
intList.add(new Integer(0));
Integer x = (Integer) intList.iterator.next();

The casting is annoying, prone to error, and introduces clutter.

3) Less clutter

Lastly, generics gets rid of clutter by allowing programmers to express their intent, and mark the object with a particular data type.

LinkedList<Integer> intList = new LinkedList<>();
intList.add(new Integer(0));
Integer x = intList.iterator().next();

When we use List<Integer> we are declaring that we have not just a list, but one of type Integer. So the compiler checks that everything we use with add() is an Integer value.

Additionally, when we access our intList, Java knows that it will return an Integer. Since most errors arise in compile time, this saves us loads of time from debugging runtime errors.

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Effective Java

Learn Enterprise Java Development for a Bright Career Try Java

Are you looking for a deeper understanding of the Java so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.

$ Check price
54.9954.99Amazon 4.5 logo(219+ reviews)

More Java resources