0

I have a question about this foreach:

    for(Element e : nullProof(setOfElements)){
            // do stuff
    }

Let's assume I defined the function, nullProof, to return a non-null Set (because I heard you shouldn't pass null into an enhanced for-loop. Is this true?):

    private Set<Element> nullProof(Set<Element> s){
          return s == null ? Collections.<Element> emptySet() : s;
    }

My question is...is it safe to call the nullProof function within the foreach? Specifically, is the following header equivalent to:

    for(Element e : setOfElements){    //assuming setOfElements != null

I was wondering if someone could point me to some Java standard that says this is defined behavior.

Furthermore, can someone explain what actually happens "behind the scenes" when this foreach is called?

Let's say setOfElements has size 6. For each iteration through setOfElements, does the JVM look up setOfElements 6 different times, or does it create a copy of that set and refer to the copy? I'm trying to understand the behavior. Thanks for the help!

sepp2k
  • 363,768
  • 54
  • 674
  • 675
touch my body
  • 1,634
  • 22
  • 36

2 Answers2

6

Yes it is perfectly safe.

for(Element e :  nullProof(setOfElements)) {

is equivalent to

Set<Element> s = nullProof(setOfElements);
for(Element e :  s) {

As stated in the JLS-14, behind the scene the for each loop is equivalent to:

for(Iterator<Element> it = s.iterator() ; it.hasNext() ; ) {
    Element e = it.next();
    // ...
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
2

It's safe because the actual collection must be resolved before any iteration takes place, but it masks your intention somewhat. In my opinion this is clearer:

if (setOfElements != null) {
    for (Element e : setOfElements) {
        ...
    }
}

Or, you might want to reevaluate why you allow setOfElements to be null at all. Does it make sense to have it be an empty list in the first place, as opposed to null?


Let's say setOfElements has size 6. For each iteration through setOfElements, does the JVM look up setOfElements 6 different times, or does it create a copy of that set and refer to the copy? I'm trying to understand the behavior.

No copying is involved. The enhanced for-loop uses an Iterator (as returned by the iterator method of any collection) to do its iteration. An Iterator is an object that is able to give you the elements of some collection one by one through its next method.

arshajii
  • 127,459
  • 24
  • 238
  • 287