Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

97. LVTI and generic types, T

In order to understand how LVTI can be combined with generic types, let's start with an example. The following method is a classical usage case of a generic type, T:

public static <T extends Number> T add(T t) {  T temp = t;  ...  return temp;}

In this case, we can replace T with var and the code will work fine:

public static <T extends Number> T add(T t) {  var temp = t;  ...  return temp;}

So, local variables that have generic types can take advantage of LVTI. Let's look at some other examples, first using the generic type, T:

public <T extends Number> T add(T t) {  List<T> numberList = new ArrayList<T>();  numberList.add(t);  numberList.add((T) Integer.valueOf(3));  numberList.add((T) Double.valueOf(3.9)); // error: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content