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.
There are three main reasons we use Java generics.
We can re-use the same code with different parameters types.
LinkedList<Integer> intList = new LinkedList<>(); LinkedList<String> stringList = new LinkedList<>();
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.
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.
The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.$ Check price
Designed for serious programmers, this reliable, unbiased, no-nonsense tutorial illuminates advanced Java language and library features with thoroughly tested code examples. As in previous editions, all code is easy to understand and displays modern best-practice solutions to the realworld challenges faced by professional developers.$ Check price