Working with generics
We have been working with generics in this chapter. Generics are flexible and used for (amongst others) collections. We were passing in values to these collections by the specified type between the angle brackets. We can create a collection with a type parameter like this:
List<String> names = new ArrayList<>();
This is because the List
interface and the ArrayList
class are created with a type parameter (generic). This makes the class a lot more flexible, while still ensuring type safety. Let’s have a look at how this was done before generics to understand why they are so great.
Life before generics – objects
When we didn’t have generics, all collections would have objects. You’d have to manually check to make sure the item in the list was of the type you hoped it was. And if it was, you’d have to cast it to this type to use this, much like this:
List = new ArrayList();list.add("Hello"); list...