简体   繁体   中英

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 ?

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.

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.

The purpose of providing a type argument for an Iterator< T >/List< T > is type-safety ,ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM