简体   繁体   English

传递多维数组

[英]Passing multi-dimensional arrays

I wrote the following code. 我写了下面的代码。 It works great, but I have a question (so I don't bomb any future additions). 它很好用,但是我有一个问题(所以我以后不添加任何炸弹)。 Here's the code: 这是代码:

public class MoreStuff extends javax.swing.JFrame {

// Globals
int quiz[][]; // Used for Quiz subroutines


...


private void btnGetQuizActionPerformed(java.awt.event.ActionEvent evt) {                                           

    Functions fns = new Functions(); 
    String strout;
    int i = 0;

    // Get the quiz
    quiz = fns.GetQuiz();

The fns.GetQuiz() returns a 2-dimensional array perfectly. fns.GetQuiz()完美返回二维数组。

My question is this: Having declared a multidimensional array at the class level, when the computer executes quiz = fns.GetQuiz, have I passed an object or have I only copied a reference? 我的问题是:在类级别上声明了多维数组后,当计算机执行quiz = fns.GetQuiz时,我是否传递了对象或仅复制了引用?

Let's say GetQuiz() 's implementation is simply: 假设GetQuiz()的实现很简单:

public int[][] GetQuiz() {
    int[][] someArray = new int[10][];
    return someArray;
}

The line int[][] someArray = new int[10][]; int[][] someArray = new int[10][]; allocates an array on the heap and assigns a reference to that object to someArray . 在堆上分配一个数组,并将对该对象的引用分配给someArray

When the method GetQuiz() finishes executing, the only thing "destroyed" is someArray , which is simply the reference to the array. 当方法GetQuiz()完成执行时,唯一被“破坏”的是someArray ,它只是对数组的引用。 The array itself lives on the heap, and only becomes eligible for garbage collection once there are no more references to the array. 数组本身位于堆上,并且仅在不再有对该数组的引用时才有资格进行垃圾回收。

In your example, because a copy of the reference is assigned to the quiz variable, even when someArray is destroyed, you still have quiz 's reference pointing to the array, so the garbage collector will not try to destroy the array. 在您的示例中,由于引用的副本已分配给quiz变量,即使当someArray被销毁时,您仍然具有指向数组的quiz引用,因此垃圾收集器不会尝试破坏数组。

I think you might find the information in this thread helpful: Stack and Heap memory in Java . 我认为您可能会在此线程中找到有用的信息: Java中的堆栈和堆内存

在你的程序中, quiz甚至会执行后保持其价值btnGetQuizActionPerformed()因为它接收参考的副本fns

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

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