I have a code snippet as shown below:
ArrayList<Integer> a = new ArrayList<Integer>();
ListIterator<Integer> p = a.listIterator();
However, I noticed that you don’t really need to specify the for the ListIterator so the code works same without it:
ArrayList<Integer> a = new ArrayList<Integer>();
ListIterator p = a.listIterator();
I think the same is als true for Iterator. So my question is when do I have to specify the type for a ListIterator/Iterator ? Is it something optional that can be used be more verbose ?
The reason to specify the generic type for the iterator is so you can extract the item it retrieves without casting. This adds a bit of compile-time type safety with no additional significant overhead, so I see no reason not to do this.