0

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?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
user3746504
  • 103
  • 1
  • HashMap & TreeMap are not part of the Collections interface – CMPS Jun 21 '14 at 02:35
  • @Amir they don't implement `Collection`, but they are part of what Oracle calls [the collections framework](http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html). – yshavit Jun 21 '14 at 03:21

1 Answers1

3

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

Typo
  • 1,875
  • 1
  • 19
  • 32