Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8331543

Avoid allocating iterators in Collections when it is empty

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      The code `for (Map.Entry<Integer, Field> entry : treeMap.entrySet()) { ... }`, if `treeMap` is empty, could the JDK return a singleton immutable iterator (Collections.emptyIterator()), which avoids allocating an Iterator?

      I have just been refactoring some protocol buffer code to avoid generating the iterator and while I'm happy to do this in code consuming the TreeMap API, I wonder if there's an opportunity here to fix this for everyone so that an empty collection doesn't allocate an iterator when you call .iterator().

      Perhaps this may not always be possible, due to fail-fast error detecting iterators that throw ConcurrentModificationException. Or perhaps there's some wiggle room that defining an iterator when the collection is empty, it's always reasonable to iterate nothing, even if it changes afterwards.

      In the TreeMap example, the iterators are eager: EntrySet.iterator() returns `new EntryIterator(getFirstEntry())`, and if getFirstEntry() is null, it will have the same behaviour as Collections.emptyIterator(); there is no modCount checking if the map is empty to start with. This is what gives me hope this is feasible to do, at least in the TreeMap case, without it being a breaking change.



            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: