在Java中创建自定义对象数组 [英] Creating array of custom objects in java
问题描述
我有100条数据记录,这些记录是通过服务进入我的系统的.我想为每个记录创建100个类对象,以将其序列化到我的自定义类.我正在如下的for循环中进行内存创建
I have a 100 records of data which is coming to my system from a service. I want to create 100 Class Objects for each record for serializing it to my Custom Class. I was doing this memory creation inside a for loop as follows
for(int i=0; i < 100; i++)
{
SomeClass s1 = new SomeClass();
//here i assign data to s1 that i received from service
}
有什么方法可以在数组外创建所有100个对象,而只需在for循环内分配数据.
Is there any way to create all the 100 objects outside the array and just assign data inside the for loop.
I already tried Array.newInstance and SomeClass[] s1 = new SomeClass[100]
两个结果都为空指针数组.有什么办法可以在for循环之外分配所有内存.
Both result in array of null pointers. Is there any way i can allocate all the memory outside the for loop.
推荐答案
执行此操作时:
Object[] myArray = new Object[100]
Java分配了100个放置对象的位置.它不会为您实例化对象.
Java allocates 100 places to put your objects in. It does NOT instantiate your objects for you.
您可以执行以下操作:
SomeClass[] array = new SomeClass[100];
for (int i = 0; i < 100; i++) {
SomeClass someObject = new SomeClass();
// set properties
array[i] = someObject;
}
这篇关于在Java中创建自定义对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!