Type inference with generics

Generics were introduced in Java to promote type safety. It enabled developers to specify their intentions of using classes, interfaces, and collection classes with fixed types or a range of types. Violations of these intentions were enforced with compilation errors, rather than runtime exceptions, raising the compliance bar.

For example, the following shows how you would define ArrayList to store String values (repeating <String> is optional, on the right-hand side of the assignment):

List<String> names = new ArrayList<>();  

However, replacing List<String> with var will put the type safety of the generics at stake:

var names = new ArrayList<>(); 
names.add(1); 
names.add("Mala"); 
names.add(10.9); 
names.add(true); 

The preceding code allows for the addition of multiple data types to names, which is not the intention. With generics, the preferred approach is to make relevant information available to the compiler, so that it can infer its type correctly:

var names = new ArrayList<String>(); 
When using var with generics, ensure that you pass the relevant data types within the angular brackets on the right-hand side of the assignment, so that you don't lose type safety.

Now, it's time for our next code check.

..................Content has been hidden....................

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