当执行下面的代码时,我想知道JVM是如何形成内存分配的。编译时内存发生了什么,执行时发生了什么,等等(如果您的回答是引用java内存模型或可能是可视化的),谢谢
PS。这个问题不是关于list of arrays in java的
List<int[]> arList = new ArrayList<>();
arList.add(new int[]{1,2});
arList.add(new int[]{1,2,3,4});
int n = (int)Math.random()*10;
int [] a = new int[n];
arList.add(a);发布于 2014-09-21 20:36:39
ArrayList和所有3个int数组都是以(或多或少)正常的方式在堆中创建的(至少只要JITC不做堆栈分配--对于非循环的main方法,它永远不会这样做)。
import java.util.*;
public class IntArrays {
public static void main(String[] args) {
List<int[]> arList = new ArrayList<>();
arList.add(new int[]{1,2});
arList.add(new int[]{1,2,3,4});
int n = (int)Math.random()*10;
int [] a = new int[n];
arList.add(a);
}
}拆卸:
C:\JavaTools>javap -c IntArrays.class
Compiled from "IntArrays.java"
public class IntArrays {
public IntArrays();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2 // class java/util/ArrayList
3: dup
4: invokespecial #3 // Method java/util/ArrayList."<init
>":()V
7: astore_1
8: aload_1
9: iconst_2
10: newarray int <<< Create the first array
12: dup
13: iconst_0
14: iconst_1
15: iastore
16: dup
17: iconst_1
18: iconst_2
19: iastore
20: invokeinterface #4, 2 // InterfaceMethod java/util/List.ad
d:(Ljava/lang/Object;)Z
25: pop
26: aload_1
27: iconst_4
28: newarray int <<< Create the second array
30: dup
31: iconst_0
32: iconst_1
33: iastore
34: dup
35: iconst_1
36: iconst_2
37: iastore
38: dup
39: iconst_2
40: iconst_3
41: iastore
42: dup
43: iconst_3
44: iconst_4
45: iastore
46: invokeinterface #4, 2 // InterfaceMethod java/util/List.ad
d:(Ljava/lang/Object;)Z
51: pop
52: invokestatic #5 // Method java/lang/Math.random:()D
55: d2i
56: bipush 10
58: imul
59: istore_2
60: iload_2
61: newarray int <<< Create the 3rd array
63: astore_3
64: aload_1
65: aload_3
66: invokeinterface #4, 2 // InterfaceMethod java/util/List.ad
d:(Ljava/lang/Object;)Z
71: pop
72: return
}未知的是ArrayList内部创建了多少个对象。在最简单的情况下,会有一个对象数组(这就是我在JDK 6源代码副本中看到的),但是没有什么可以阻止实现使用某种类型的链接列表,如果每个元素都是一个单独的对象,或者其他一些方案。
发布于 2014-09-21 20:35:31
只是为了添加一些视觉的东西。这是我不久前在JCP预备课上从一个更抽象的层面上学到的。(嗯,不完全是这样。但是.
runtime stack
+---+
| a | --------------------------------------+
+---+ |
+---+ |
| n | |
+---+ |
+--------+ |
| arList | --+ |
+--------+ | |
| |
| runtime heap |
v |
+-----------+ +-------+ |
| ArrayList | --> | 1 | 2 | |
+-----------+ +-------+ |
| | +---------------+ |
| +-----> | 1 | 2 | 3 | 4 | |
| +---------------+ v
| +---+-...
+-----------------------------> | 0 | {n times}
+---+-...我认为在它成为具体实现之前,这是最不常见的。
https://stackoverflow.com/questions/25963222
复制相似问题