在java中创建自定义对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20402764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:41:52  来源:igfitidea点击:

Creating array of custom objects in java

javaarrays

提问by kishore

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

我有 100 条数据记录,这些数据从服务传入我的系统。我想为每条记录创建 100 个类对象,以便将其序列化为我的自定义类。我在 for 循环中创建内存如下

for(int i=0; i < 100; i++)
{
SomeClass s1 = new SomeClass();
//here i assign data to s1 that i received from service
}

Is there any way to create all the 100 objects outside the array and just assign data inside the for loop.

有什么方法可以在数组外创建所有 100 个对象,并在 for 循环内分配数据。

I already tried Array.newInstance and SomeClass[] s1 = new SomeClass[100]

Both result in array of null pointers. Is there any way i can allocate all the memory outside the for loop.

两者都会导致空指针数组。有什么办法可以在for循环之外分配所有内存。

采纳答案by ioreskovic

When you do this:

当你这样做时:

Object[] myArray = new Object[100]

Java allocates 100 places to put your objects in. It does NOT instantiate your objects for you.

Java 分配了 100 个位置来放置您的对象。它不会为您实例化您的对象。

You can do this:

你可以这样做:

SomeClass[] array = new SomeClass[100];

for (int i = 0; i < 100; i++) {
    SomeClass someObject = new SomeClass();
    // set properties
    array[i] = someObject;
}

回答by Harshil

I found below really helpful when creating array of custom objects in single line:

在单行中创建自定义对象数组时,我发现下面非常有用:

public class Hotel {
    private int frequency;
    private String name;
    public Hotel(int frequency,String name){
        this.frequency = frequency;
        this.name = name;
    }
}
public class PriorityQueueTester {
    public static void main(String args[]){
        Queue<Hotel> hotelPQ = new PriorityQueue<Hotel>();
        Hotel h[] = new Hotel[]{new Hotel(4,"Harshil"),new Hotel(5,"Devarshi"),new Hotel(6,"Mansi")};
        System.out.println(h[0].getName() + " "+h[1].getName()+" "+h[2].getName());
    } 
}