如何在 Java 中分配对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31394904/
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-11-02 18:32:55  来源:igfitidea点击:

How do I allocate array of objects in Java?

javaarrays

提问by cpx

I've been allocating arrays using the following syntax while going through some Java tutorials so far:

到目前为止,我一直在使用以下语法分配数组,同时浏览一些 Java 教程:

// Ok, all the elements are zero upon creation
int[] a = new int[5];

// I can set all the elements however I want!
for (int i = 0; i < a.length; i++)
     a[i] = i+1

But since when I started using a class, things have been confusing me:

但是自从我开始使用一个类以来,事情一直让我感到困惑:

class Employee
{
    public Employee(String name, int age) {
         emp_name = n;
         emp_age = a;
    }

    void setName(String name) {
          emp_name = name;
    }

    void setAge(int age) {
          emp_age = age;
    }

    private String emp_name;
    private String emp_age;

}

I use this class in the main function like the following:

我在主函数中使用这个类,如下所示:

Employee[] staff = new Employee[3];

This line should give me an array of three objects default initialized by the constructor as I assume.

正如我所假设的,这一行应该给我一个由构造函数默认初始化的三个对象的数组。

When I do the following I get an exception on the runtime.

当我执行以下操作时,我在运行时遇到异常。

staff[0].setName("Test");

In C++, this has been be fairy simple which doesn't require an extra new:

在 C++ 中,这非常简单,不需要额外的new

Employee *e[3];

So, upon further searching something tells me that I still need to allocate memory for each of the elements in array to actually start using them. If so, then what was the purpose of using newoperator? Doesn't it already allocate memory for the array? How come this doesn't happen with intarray?

因此,在进一步搜索后,一些信息告诉我,我仍然需要为数组中的每个元素分配内存才能真正开始使用它们。如果是这样,那么使用new运算符的目的是什么?它不是已经为数组分配了内存吗?为什么这不会发生在int数组中?

回答by Tot Zam

When you create an array of Objects, you create an array full of nullobjects. The array is full of "nothingness". An Employeewill not be created until you explicitly create one.

当你创建一个对象数组时,你创建了一个充满null对象的数组。阵中充满了“虚无”。一个Employee不会被创建,直到你明确地创建一个。

Employee[] staff = new Employee[3];

At this point your array looks like:

此时你的数组看起来像:

[null] [null] [null]

[空] [空] [空]

You can then create an Employee by doing:

然后,您可以通过执行以下操作来创建 Employee:

staff[0] = new Employee();

At this point, your default Employee constructor is called and your array now has an Employeeobject in the first position:

此时,您的默认 Employee 构造函数被调用,并且您的数组现在Employee在第一个位置有一个对象:

[Employee1][null][null]

[员工 1][空][空]

Now that you have an actual Employeein the first position, you should be able to call:

现在您Employee在第一个位置有一个实际,您应该可以调用:

staff[0].setName("Test");

Update:

更新:

In regard to the question:

关于这个问题:

what was the purpose of using new operator? Doesn't it already allocate memory for the array? How come this doesn't happen with int array?

使用 new 运算符的目的是什么?它不是已经为数组分配了内存吗?为什么 int 数组不会发生这种情况?

Similar questions were already asked hereand here. In short, when you create the array of Objects, you really create an array of references. At first, all these references just point to null objects. When you do staff[0] = new Employee();, you are in essence doing two things:

类似的问题已经在这里这里提出。简而言之,当您创建对象数组时,您实际上创建了一个引用数组。起初,所有这些引用都指向空对象。当你这样做时staff[0] = new Employee();,你本质上是在做两件事:

  1. Creating and allocating memory for a "new" Employee
  2. Telling staff[0]to now point to the new Employee object instead of null
  1. 为“新”员工创建和分配内存
  2. 告诉staff[0]现在指向新的 Employee 对象而不是null

回答by Adam Evans

In Java, all "objects" are actually just references (pointers, sort of). So you are correct in assuming that Java auto-initializes the values in the array, but in your second array, you have an array of references, which are basically memory addresses, and therefore are initialized to null.

在 Java 中,所有“对象”实际上只是引用(指针,某种意义上)。因此,您假设 Java 自动初始化数组中的值是正确的,但是在您的第二个数组中,您有一个引用数组,它们基本上是内存地址,因此被初始化为null.

You are getting your exception because you are calling a method on a nullreference. Also, notice that when you created an array of primitives, you are using the assignment operator with the different indices in the array. In your example with objects, you are just immediately using the values in the array, not assigning them. So technically, what you were doing in the primitive array example can be done with object arrays, since it is simple assignment.

您收到异常是因为您正在调用null引用的方法。另外,请注意,当您创建基元数组时,您使用的是具有数组中不同索引的赋值运算符。在您的对象示例中,您只是立即使用数组中的值,而不是分配它们。所以从技术上讲,你在原始数组示例中所做的可以用对象数组来完成,因为它是简单的赋值。

回答by Subler

In Java, when you create an array of objects, the default values of every entry in the array is null. There are no constructors being called. You'll have to loop over the array and create an object for each entry.

在 Java 中,当您创建对象数组时,数组中每个条目的默认值都是null。没有调用构造函数。您必须遍历数组并为每个条目创建一个对象。

for example

例如

for(int i=0; i<staff.length; i++){
    staff[i] = new Employee("name" + i, 20);
}