通过for循环添加具有不同名称的对象 [英] add objects with different name through for loop

查看:229
本文介绍了通过for循环添加具有不同名称的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作的最佳方式是:

What is the best way to do the following:

List<MyObject> list = new LinkedList<MyObject>();

for(int i=0; i<30;i++)
{
  MyObject o1 = new MyObject();
  list.add(o1);
}

但事情是我不想创建具有相同名称的对象,我想用不同的名称创建它们,如 o1,o2,o3,o4,o5,o6,o7,o8,o9,o10 ,我想将每个名称添加到列表中。最好的方法是什么?

But the things is I don't wanna create objects with same name, I wanna create them with different name like o1,o2,o3,o4,o5,o6,o7,o8,o9,o10 and I wanna add each to the list. What is the best way to do this ?

推荐答案

您不需要为每个对象使用不同的名称。由于o1对象是在for循环中声明的,因此o1变量的范围仅限于for循环,并且在每次迭代期间重新创建...除非每次它将引用在该迭代期间创建的新对象。请注意,变量本身不存储在列表中,只存储在它所引用的对象中。

You don't need to use a different name for each object. Since the o1 object is declared within the for loop, the scope of the o1 variable is limited to the for loop and it is recreated during each iteration ... except each time it will refer to the new object created during that iteration. Note that the variable itself is not stored within the list, only the object that it is referring to.

如果您不需要对新对象执行任何其他操作除了将其添加到列表之外,您可以执行以下操作:

If you don't need to do anything else with the new object other than add it to the list, you can do:

for(int i=0; i<30;i++)
{
  list.add(new MyObject());
}

这篇关于通过for循环添加具有不同名称的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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