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?

2
  • HashMap & TreeMap are not part of the Collections interface Commented Jun 21, 2014 at 2:35
  • @Amir they don't implement Collection, but they are part of what Oracle calls the collections framework. Commented Jun 21, 2014 at 3:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.