如何在Java中创建对象引用数组? [英] How to create array of object references in Java?

查看:201
本文介绍了如何在Java中创建对象引用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个类创建对象引用的数组,但不想实际创建要分配给array的对象。我该怎么办。 ?

I want to create an array of object references for a class , but don't want to actually create objects to assign into array . How can I do so. ?

推荐答案

数组用于存储原始值和对象。例如,我们可以创建String数组或任何类对象。
为了说明,让我们创建一个包含单个实例变量empId的Employee类。以下是此类的定义。

Arrays are used to store primitive values and objects. For example, we can create an array of String or any class objects. To explain, Lets create a class Employee containing a single instance variable empId. Following is the definition of this class.

class Employee{
   int empId;
}

创建对象数组就像在其中创建原始类型数据项的数组一样以下方式。

An array of objects is created just like an array of primitive type data items in the following way.

Employee[] EmployeeArray = new Employee[10];

上面的语句创建了一个数组,该数组可以保存对十个Employee对象的引用。它不会自己创建Employee对象。
必须使用Employee类的构造函数分别创建它们。 EmployeeArray包含十个内存空间,其中可以存储十个Employee对象的
地址。如果我们甚至在创建Employee对象之前尝试访问它们,就会发生运行时错误。

The above statement creates the array which can hold references to ten Employee objects. It doesn't create the Employee objects themselves. They have to be created separately using the constructor of the Employee class. The EmployeeArray contains ten memory spaces in which the address of ten Employee objects may be stored. If we try to access the Employee objects even before creating them, run time errors would occur.

必须使用Employee类的构造函数实例化Employee对象,并且应通过以下方式将其引用分配给数组元素。

The Employee objects have to be instantiated using the constructor of the Employee class and their references should be assigned to the array elements in the following way.

EmployeeArray[0] = new Employee();

通过这种方式,我们还创建了其他Employee对象。如果必须使用不同的构造函数来创建每个Employee对象,则我们将使用类似于上述几次的语句。但是,在这种特殊情况下,由于所有Employee对象都是使用相同的默认构造函数创建的,因此我们可以使用for循环。

In this way, we create the other Employee objects also. If each of the Employee objects have to be created using a different constructor, we use a statement similar to the above several times. However, in this particular case, we may use a for loop since all Employee objects are created with the same default constructor.

for ( int i=0; i<EmployeeArray.length; i++) {
EmployeeArray[i]=new Employee();
}

上面的for循环创建十个Employee对象,并将它们的引用分配给数组元素。

The above for loop creates ten Employee objects and assigns their reference to the array elements.

这篇关于如何在Java中创建对象引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆