jvm如何处理在循环内创建对象 [英] how jvm handles creating object inside a loop

查看:225
本文介绍了jvm如何处理在循环内创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List list = new ArrayList();


String[] test = {"ram", "mohan", "anil", "mukesh", "mittal"};

for(int i =0; i < test.length; i++)

{

  A a = new A();

  a.setName(test[i]);

  list.add(a);

}

JVM如何在每个循环中处理对象a的创建?不同实例之间的列表"如何区分?在每次迭代中创建对象是一种好习惯.如果没有,将对象添加到列表中的最佳解决方案是什么.

How JVM handles creation of object a in each loop? How "list" differntiate between different instance? Is it good practice to create object on each iteration. If no, what is the best solution for adding object into a list.

推荐答案

在您的示例中,循环的每次迭代都会创建一个新对象.该列表能够区分它们,因为它并不关心您在代码中将它们全都称为"a",而是通过每次调用时都会重新分配的引用来跟踪它们.

In your example a new object is created on each iteration of the loop. The list is able to differentiate between them because it does not care that you call them all "a" in your code, it keeps track of them by the reference that gets reassigned each time you call

a = new A();

每次调用该行代码时,都会在堆上创建一个新对象,并将其在内存中的地址分配给引用a.列表保留记录的是引用,而不是变量名.

Each time that line of code is called, a new object is created on the heap and it's address in memory is assigned to the reference a. It's that reference that the list keeps a record of, not the variable name.

这是填充列表的一种很好的方法,这是正常的(除了其他人提到的语法错误,我认为在尝试编译代码时可以修复).

This is a perfectly fine and normal way to populate a list (aside from the syntax errors that others have mentioned, which I'm assuming you can fix when you try to compile your code).

这篇关于jvm如何处理在循环内创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆