我是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类如下:
class A{
int rollno;
int DOB;
}
你想为类a创建一个对象数组,你这样做,
A[] arr = new A[4]; //Statement 1
for (int i = 0; i < 4; i++) {
arr[i] = new A(); //Statement 2
}
这完全正确。
Here A is the class and in Statement 1 Class A is a datatype of the array. When this statement gets executed because of the new keyword an object is created and dynamically memory is allocated to it which will be equal to the space required for the 4 blocks of datatype A i.e, ( for one block in the array space required is 8 bytes (4+4), I am assuming int takes 4 bytes of space. therefore total space allocated is 4*4 bytes for the array ).
Then the reference of the object is given to the arr variable. Here important point to note is that Statement 1 has nothing to do with creating an object for class A ,no object is created for this class it is only used as a datatype which gives the size of the class A required for the memory allocation of the array.
然后,当for循环运行和语句2执行时,JVM现在为类A分配内存(即创建一个对象),并将其引用给arr[i]。每次调用循环时,都会创建一个对象,并将其引用给arr[i]。
因此,拥有8字节空间的arr[0]被赋予a类对象的引用,每次运行time循环都会创建一个新对象,并给予该对象引用,以便它现在可以访问该对象中的数据。
你说得对。除此之外,如果我们想创建一个特定大小的数组,填充一些“工厂”提供的元素,因为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等生成器。