Java的foreach是否创建副本? [英] Does Java foreach create copies?

查看:144
本文介绍了Java的foreach是否创建副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



$ p $ for(Element e:nullProof(setOfElements)){
我们假设我定义了函数nullProof,返回一个值为0的数组。非空set(因为我听说你不应该将null传入一个增强的for循环中,这是真的吗?):
$ b $ $ pre $ code > private Set< Element> nullProof(Set< Element> s){
return s == null?类别<组件> emptySet():s;

$ / code>

我的问题是...可以安全地调用 nullProof在foreach中的函数?具体来说,下面的头文件相当于:

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

我想知道是否有人可以指向我的一些Java标准,说这是定义的行为。



另外,有人可以解释一下在这个foreach被调用的时候,幕后实际发生了什么吗?

比方说 setOfElements 的大小为6.对于通过 setOfElements 进行的每次迭代,JVM是否查找 setOfElements 6次,或者是否创建该set的副本并引用到副本?我试图理解这个行为。感谢您的帮助!

解决方案

是的,它是完全安全的。 (元素e:nullProof(setOfElements)){

相当于

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

正如 JLS-14 后面(Iterator< Element> it = s.iterator());这个场景 ); it.hasNext();){
Element e = it.next();
// ...
}


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!

解决方案

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();
    // ...
}

这篇关于Java的foreach是否创建副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆