简体   繁体   English

用Java创建数组对象?

[英]Creating Array Objects in Java?

I'm quite new to Java and had a little problem concerning arrays. 我是Java的新手,在数组方面有一些问题。 In an exercise given one had to create a class named "Exam" with a method "addExam". 在给定的练习中,必须使用方法“ addExam”创建一个名为“ Exam”的类。 Now I tried to solve the problem but only got to the definition of the cass, the instance variables and the method heading. 现在,我尝试解决该问题,但仅涉及Cass的定义,实例变量和方法标题。 The rest I looked up in the solution and it looked like: 其余的我在解决方案中查找,看起来像:

public class Exam{
private int numberOfExams=15;
private Exam[]exams = new Exam[numberOfExams];

public void addExam(Exam exam){
exams[numberOfExams] = exam;
numberOfExams++;

So now to my question: When I assign "exam" to the array exams in the method addExam, is a new object created here? 现在,我的问题是:当我在方法addExam中为数组检查分配“检查”时,是否在此处创建了新对象? And when yes, why aren't bracktes and the "new operator" used? 当是的时候,为什么不使用粗体字和“新操作符”呢? This question leads to a more general one: I know that arrays are of a class type, do they now create array objects or variables of that array type? 这个问题导致了一个更笼统的问题:我知道数组属于类类型,它们现在是否创建数组对象或该数组类型的变量?

I really need some help! 我真的需要一些帮助!

public void addExam(Exam exam){
exams[numberOfExams] = exam;

No. No new object created, what ever the object passed here assigned to the 0th element of your array. 不会。没有创建新对象,这里传递的对象将分配给数组的第0个元素。

The actual place of creating new object is the place where addExam method called. 创建新对象的实际位置是addExam方法调用的位置。 Something like 就像是

Exam exam = new Exam();
// do something
addExam(exam);

When I assign "exam" to the array exams in the method addExam, is a new object created here? 当我在方法addExam中为数组检查分配“检查”时,是否在此处创建了新对象?

No . 不行 A reference to the existing Exam instance will be added to the array. 对现有Exam实例的引用将添加到数组中。 So, you will have 2 references to the same instance of Exam 因此,您将有2个对同一Exam实例的引用

When you assign an "exam" to the array, it doesn't create a new object. 当您为数组分配“检查”时,它不会创建新对象。 It merely stores the reference of an existing object in the array. 它仅将现有对象的引用存储在数组中。

If I understand your second question, when you create an array with a call such as Exam[] exams = new Exam[numberOfExams]; 如果我理解您的第二个问题,那么当您通过调用创建数组时,例如Exam[] exams = new Exam[numberOfExams]; you create an object that contains enough space for numberOfExams references to Exam objects. 您创建了一个对象,该对象包含足够的空间用于对Exam对象的numberOfExams引用。

BTW, exams[numberOfExams] = exam; BTW, exams[numberOfExams] = exam; would give you an ArrayIndexOutOfBoundsException , since your array has numberOfExams elements, so the valid indices are from 0 to numberOfExams-1 . 会给您一个ArrayIndexOutOfBoundsException ,因为您的数组具有numberOfExams元素,所以有效索引从0到numberOfExams-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM