我是Java的新手,在Java中创建了一个对象数组。

我有一个a类的例子

A[] arr = new A[4];

但这只是创建指向A的指针(引用),而不是4个对象。这对吗?我看到,当我试图访问创建的对象中的函数/变量时,我得到一个空指针异常。 为了能够操作/访问对象,我必须这样做:

A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
    arr[i] = new A();
}

这是正确的还是我做错了什么?如果这是正确的,那真的很奇怪。

编辑:我觉得这很奇怪,因为在c++中,你只需输入new A[4],它就创建了四个对象。


当前回答

这是正确的。

A[] a = new A[4];

...创建4个A引用,类似于这样做:

A a1;
A a2;
A a3;
A a4;

现在你不能执行a1. somemethod()而不像这样分配a1:

a1 = new A();

类似地,对于数组,你需要这样做:

a[0] = new A();

...使用前。

其他回答

对于泛型类,有必要创建包装器类。 例如:

Set<String>[] sets = new HashSet<>[10]

结果:"不能创建通用数组"

使用:

        class SetOfS{public Set<String> set = new HashSet<>();}
        SetOfS[] sets = new SetOfS[10];  

下面是创建一个包含10个雇员对象的数组的清晰示例,并带有一个带形参的构造函数:

public class MainClass
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
        //step1 : first create array of 10 elements that holds object addresses.
        Emp[] employees = new Emp[10];
        //step2 : now create objects in a loop.
        for(int i=0; i<employees.length; i++){
            employees[i] = new Emp(i+1);//this will call constructor.
        }
    }
}

class Emp{
    int eno;
    public Emp(int no){
        eno = no;
        System.out.println("emp constructor called..eno is.."+eno);
    }
}

是的,它只创建被设置为默认值null的引用。这就是为什么你会得到一个NullPointerException。你需要单独创建对象并分配引用。在Java中创建数组有3个步骤

Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty. Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions. Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations. Declaring Arrays In Java This is how we declare a one-dimensional array in Java – int[] array; int array[]; Oracle recommends that you use the former syntax for declaring arrays. Here are some other examples of legal declarations – // One Dimensional Arrays int[] intArray; // Good double[] doubleArray; // One Dimensional Arrays byte byteArray[]; // Ugly! long longArray[]; // Two Dimensional Arrays int[][] int2DArray; // Good double[][] double2DArray; // Two Dimensional Arrays byte[] byte2DArray[]; // Ugly long[] long2DArray[]; And these are some examples of illegal declarations – int[5] intArray; // Don't mention size! double{} doubleArray; // Square Brackets please! Instantiation This is how we “instantiate”, or allocate memory for an array – int[] array = new int[5]; When the JVM encounters the new keyword, it understands that it must allocate memory for something. And by specifying int[5], we mean that we want an array of ints, of size 5. So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of type int[] Initialization Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you. All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax – int[] arr = {1, 2, 3, 4, 5}; Here, we don’t mention the size, because JVM can see that we are giving 5 values.

因此,在实例化引用之前,引用始终为空。希望我的回答对你有所帮助!:)

源- Java中的数组

你说得对。除此之外,如果我们想创建一个特定大小的数组,填充一些“工厂”提供的元素,因为Java 8(引入了流API),我们可以使用下面的一行程序:

A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);

Stream.generate(() -> new A())类似于以lambda, () -> new A()描述的方式创建的单独A元素的工厂,它是Supplier<A>的实现-它描述了应该如何创建每个新A实例。 Limit(4)设置流将生成的元素数量 toArray(A[]::new)(也可以重写为toArray(size -> new A[size])) -它让我们决定/描述应该返回的数组类型。

对于一些基本类型,你可以使用DoubleStream, IntStream, LongStream,它们还提供了诸如range rangecclosed等生成器。

是的,在Java中这是正确的,有几个步骤来创建一个对象数组:

声明,然后实例化(创建内存存储'4'对象): A[] arr = new A[4]; 初始化对象(在这种情况下,你可以初始化类A的4个对象) arr[0] = new A(); arr[1] = new A(); arr[2] = new A(); arr[3] = new A(); 或 For (int i=0;我< 4;我+ +) arr[i] = new A();

现在你可以开始从你刚刚创建的对象中调用现有的方法了。

例如:

  int x = arr[1].getNumber();

or

  arr[1].setNumber(x);