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: incompatible types: String cannot be converted to T
// numbers.add("5");

return numberList.get(0);
}

Now, let's replace List<T> with var:

public <T extends Number> T add(T t) {

var numberList = new ArrayList<T>();
numberList.add(t);
numberList.add((T) Integer.valueOf(3));
numberList.add((T) Double.valueOf(3.9));

// error: incompatible types: String cannot be converted to T
// numbers.add("5");

return numberList.get(0);
}

Pay attention and double-check the ArrayList instantiation for the presence of T. Don't do this (this will be inferred as ArrayList<Object> and will ignore the real type behind the generic type, T):

var numberList = new ArrayList<>();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157