Generics are used to create classes, interfaces and methods that take types and parameters and these parameters are called type parameters.
It is always best practice to define what type of objects a ArrayList is about to hold so that if we try to add an object of any other type rather than the one defined we will get an error at compile time itself rather than getting error at run time
For example if we dont define the type like this
ArrayList items = new ArrayList();
Above we have defined an Arraylist of raw type. Prior to java 5 that was the only way to create arraylists.
Then add a few objects of type Integer
items.add(2);
items.add(3);
Now if we try adding a String
items.add("tim");
We will only get an error at run time which is not good
So we want to get error at compile time itself so we use generics for that i.e we define our Arraylist like below The Arraylists that are created using type parameter are called generic Arraylist.
ArrayList<Integer> items = new ArrayList();
Then this will give error at compile time itself
items.add("tim");
If version of java is less than eight define object type on right side as well like this
ArrayList<Integer> items = new ArrayList<Integer>();
If we set our java version to 8 in intellij we can simply use diamonds on the right hand side while creating an arraylist. Diamonds are empty parenthesis. <>
It means that since we have already define type parameter of Integer on the right side ,we don’t have to define it again on right side
ArrayList<Integer> items = new ArrayList<>();