Search code examples
javaiteratorimplementationconcrete

Differences between standard iterator implementations


I tried searching around the site, but there is way too many threads with keywords interator or implementation. So, in a nut shell, what is the difference between various standard iterator implementations? I have not noticed anything different, besides the fact that .getClass() returns different strings.

    List myList = (List) Arrays.asList("a", "b", "c", "d");
    Set hashSet = new HashSet<String>();
    Set treeSet = new TreeSet<String>();
    ArrayList arrayList = new ArrayList<String>();
    System.out.println(arrayList.iterator().getClass());//ArrayList
    System.out.println(hashSet.iterator().getClass());//HashSet
    System.out.println(myList.iterator().getClass());//List produced by Arrays.asList()
    System.out.println(treeSet.iterator().getClass());//TreeSet

Result is as follows:

    class java.util.ArrayList$Itr
    class java.util.HashMap$KeyIterator
    class java.util.AbstractList$Itr
    class java.util.TreeMap$KeyIterator

So, why not keep the interface for people to implement in custom classes if needed, and have one concrete implementation across all Collections?


Solution

  • The diference lies in the Class used to generate the iterator, you can't expect that the same iterator implementation work on, for instance, a HashMap and a TreeMap equally.

    Check this source codes for the classes you worked with, and look for the iterator implementation:

    ArrayList: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java

    TreeMap: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/TreeMap.java?av=f

    AbstractList: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java?av=f

    HashMap: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java?av=f