Does Java foreach make copies?

I have a question about this foreach:

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

Suppose I defined a nullProof function to return a non-zero Set (because I heard that you should not pass null to the extended 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 inside foreach? In particular, the following header is equivalent:

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

I was wondering if anyone could point me to some kind of Java standard that says this is a defined behavior.

Also, 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 setOfElements work 6 times or does it create a copy of this set and refer to the copy? I am trying to understand the behavior. Thanks for the help!

0
java foreach jvm
source share
2 answers

Yes, it is absolutely safe.

 for(Element e : nullProof(setOfElements)) { 

equivalently

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

As stated in JLS-14 , backstage for each loop is equivalent to:

 for(Iterator<Element> it = s.iterator() ; it.hasNext() ; ) { Element e = it.next(); // ... } 
+6
source share

This is safe because the actual collection must be resolved before any iteration begins, but it does mask your intention a bit. In my opinion, this is clearer:

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

Or you can overestimate why you allow setOfElements be null at all. Does it make sense to have this empty list first of all instead of null ?


Let's say setOfElements has size 6. For each iteration through setOfElements does the JVM work up setOfElements 6 times or creates a copy of this set and refers to the copy? I am trying to understand the behavior.

No copying. The enhanced for -loop uses an Iterator (as returned by the Iterator any collection) to complete its iteration. Iterator is an object that can give you the elements of a collection one by one through the next method.

+2
source share

All Articles