英文:
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< 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论