在Java中的for循环内部声明一个数组。

huangapple go评论66阅读模式
英文:

declaration of an array inside the for loop in Java

问题

public class Test1 {
    public static void main() {
        int N = 10;
        int M = 100000;
        for (int i = 0; i < N; i++) {
            int[] box = new int[M];
        }
    }
}

这段代码会导致在每次循环迭代时为大小等于 M 个元素的数组分配内存吗?

英文:
public class Test1 {
    public static void main () {
        int N = 10;
        int M = 100000;
        for(int i =0; i&lt; N; i++) {
             int[] box = new int[M];
        }
    }
}

Will this code cause cause the memory to be allocated for the array with size equal to M elements for each iteration of the for loop?

答案1

得分: 2

是的。但由于循环外部不存在对新数组的引用,因此每个实例都有资格进行垃圾回收,并且很可能会在下一次gc运行时被收集起来。

英文:

Yes. But since no reference on the new array exists outside the loop, each instance is eligible for garbage-collection and will most probably be collected with the next gc-run.

huangapple
  • 本文由 发表于 2020年9月2日 23:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63708908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定