public class A { //some fields (may not only primitive types) and methods here}
public class B {// some fields (may not only primitive types) and methods here, may also have a class A reference }
Run Code Online (Sandbox Code Playgroud)
问题如下:
public class Test{
public static void main(String[] args){
A a = new A();//1. it will allocate memory for one object of A and a is the reference points to that space?
ArrayList<B> bList = new ArrayList<B>(10);//2. it will allocate memory for 10 objects of B?
ArrayList<B> bList2 = bList;//3. bList2 reference to the same location as bList?
ArrayList<B> bList3 = new ArrayList<B>(20);//4. bList3 points to a memory location which can hold 20 objects of B?
bList3 = bList;//5. bList3 now points to the same location as bList, and the space allocated in question 4 will be cleaned by garbage collector later?
ArrayList<B> bList4 = new ArrayList<B>(10);
bList4.addAll(bList);//6. it is the same as bList4 = bList;? and the memory created in above line will be cleaned by garbage collector later?
method1(bList3);//7.after this function call bList3 will point to memory space created for bLista inside the method1? and we can modify the content of that space via bList3
}
public void method1(ArrayList<B> list){
//do something here
ArrayList<B> bLista = new ArrayList<B>();
list = bLista;
}
}
Run Code Online (Sandbox Code Playgroud)
好的,这是一些真正的答案.
new运营商除非没有足够的可用内存分配.即使对象的构造函数失败,并且分配的内存很快被垃圾收集,也会临时分配新对象的空间.ArrayList不依赖于其中元素的数量,ArrayList此外,它将为10个对象创建足够的空间,这些对象不依赖于对象本身的大小; 在64位系统上,指针在32位系统上将是32位,而在某一天,64位(或者可能由某个真正智能的VM压缩到更少).ArrayList则会自动重新分配必要的存储空间.bList3可以"逃避"被强烈引用.那个未引用的对象现在有资格进行垃圾回收.bList4仍然指向同一个对象,并且该对象不能被垃圾回收.该列表引用了引用的所有元素bList,但它们不相同.特别是,对一个列表的更改不会影响另一个列表,但是通过任一列表都可以看到对列表内容的更改.| 归档时间: |
|
| 查看次数: |
690 次 |
| 最近记录: |