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!
java foreach jvm
user4343502
source share