Add using generics

Sometimes having different types in the same list is exactly what we want. But, most of the time, we would like the list to contain values of the same type. Meanwhile, code may have logical errors that allow a different type to be added to the list, which can have unexpected consequences. If it leads to throwing an exception, it is not as bad as some default conversion and incorrect results at the end, which may not be noticed for a long time, if ever.

To avoid such a problem, one can use generics that allow defining the expected type of the collection elements, so that the compiler can check and fail the case when a different type is added. Here is an example:

List<Integer> list1 = new ArrayList<>();list1.add(null);list1.add( ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.