在循环中创建对象的新实例以添加到列表中 [英] Creating new instance of object in loop to add in list

查看:45
本文介绍了在循环中创建对象的新实例以添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将对象(JavaBean)添加到列表中.

I am trying to add the object (JavaBean) into the list.

     MyWebServiceRequest mywebService = new MyWebServiceRequest();
     MyRequestType type= new MyRequestType ();

       for(int i=0; i< 9; i++){
           type.setA(someDynamicValue);
           type.setB(someDynamicValue);
           mywebService.add(type);
       }

这只会创建一个(类型)对象,因此它会向同一对象添加9次具有相同数据的数据.

This creates only one object of (type), so it add same object 9 times with same data.

 MyWebServiceRequest mywebService = new MyWebServiceRequest();
   for(int i=0; i< 9; i++){
           MyRequestType type= new MyRequestType ();
           type.setA(someDynamicValue);
           type.setB(someDynamicValue);
           mywebService.add(type);
       }

这将创建多个对象,并使用diff值添加9个diff对象.

This creates multiple objects, add 9 diff object with diff values .

如果(for循环)每次创建一个请求时都创建数百个对象而不是9个,该怎么办?那么它在内存中的转储对吗?

What if (for loop) create hundreds of objects instead of 9 in single loop , each and every time a request is made? So its dump in memory right?

如何避免这种情况?

在此先感谢.

推荐答案

执行此操作

 MyWebServiceRequest mywebService = new MyWebServiceRequest();
   MyRequestType type= new MyRequestType ();

   for(int i=0; i< 9; i++){
       type.setA(1);
       type.setB(2);
       mywebService.add(type);
   }

mywebService.add(type); 行将对象添加到列表中,无论其状态是否更改或相同.因为它是列表,而不是不允许重复的地图.

The line mywebService.add(type); adds the object into list , no matter its state is changed or not or it is the same object. Because its a list and not a Map which do not allow duplicates.

现在,当您这样做时,计数就增加到10

So the count goes to 10 , now when you do

 MyWebServiceRequest mywebService = new MyWebServiceRequest();


   for(int i=0; i< 9; i++){
       MyRequestType type= new MyRequestType ();
       type.setA(1);
       type.setB(2);
       mywebService.add(type);
   }

现在,代码创建了一个新对象并将其添加到列表中,但是每个对象都不相同.两个片段中唯一的区别是,第二个片段中的对象不相同,但第一个片段中的对象相同,但相加了10倍.

The code now makes a new object and add to list , but every object is different . The only difference in two snippets is , the Objects in the second snippet are not same , but in the first snippet its same but added 10 times.

这篇关于在循环中创建对象的新实例以添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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