Cemre Mengü
Cemre Mengü

Reputation: 18754

Java ListIterator/Iterator Type

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 ?

Upvotes: 3

Views: 4015

Answers (3)

Razvan
Razvan

Reputation: 10103

The purpose of providing a type argument for an Iterator< T >/List< T > is type-safety ,i.e. the compiler can check at compile time if there is a mismatch between the type the iterator/list can handle and what the programmer expects it to handle.

Ex:

 List aList = new ArrayList();
 Iterator it = aList.iterator();
 String s = (String)it.next() //compiles even if it iterates over a list of Integers

 List<Integer> aList = new ArrayList<Integer>();
 Iterator<Integer> it = aList.iterator();
 String s = it.next() //compilation error

Upvotes: 2

npe
npe

Reputation: 15719

What you are referring to, is called generics. It's a really powerful tool, which - amongst others - gives you type safety for collections in compile-time.

Take a look at Java Denerics documentation pages to learn when, why and how you should use them.

Now, back to your example - this code:

Iterator it1 = a.iterator();          
Iterator<Integer> it2 = a.iterator();

it1.next();    // Compiler will assume, that this returns `Object`
               // because you did not define the type of the collection element 
               // for the Iterator.

it2.next();    // Compiler will assume, that this returns `Integer` 
               // because you said so in declaration.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

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.

Upvotes: 5

Related Questions