基本的java程序问题

5Yr*_*DBA -1 java

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)

eri*_*son 5

  1. 是.
  2. 没有.
  3. 是.
  4. 有点.并不是的.这是一个棘手的问题吗?
  5. 是!
  6. 没有.
  7. 没有.

好的,这是一些真正的答案.

  1. new运营商除非没有足够的可用内存分配.即使对象的构造函数失败,并且分配的内存很快被垃圾收集,也会临时分配新对象的空间.
  2. 这为a的字段分配空间,ArrayList不依赖于其中元素的数量,ArrayList此外,它将为10个对象创建足够的空间,这些对象不依赖于对象本身的大小; 在64位系统上,指针在32位系统上将是32位,而在某一天,64位(或者可能由某个真正智能的VM压缩到更少).
  3. 这是一个简单的任务.两个变量都分配了相同的值.
  4. 最初为20个对象引用分配了内存.但是,如果列表中添加了20个以上的对象,ArrayList则会自动重新分配必要的存储空间.
  5. 是.在这种情况下,可以看到没有对最初分配给的对象的引用bList3可以"逃避"被强烈引用.那个未引用的对象现在有资格进行垃圾回收.
  6. bList4仍然指向同一个对象,并且该对象不能被垃圾回收.该列表引用了引用的所有元素bList,但它们不相同.特别是,对一个列表的更改不会影响另一个列表,但是通过任一列表都可以看到对列表内容的更改.
  7. 不,Java按值传递引用,因此方法不能使调用者的引用引用不同的对象.