简体   繁体   中英

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.

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?

Let's say GetQuiz() 's implementation is simply:

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

The line int[][] someArray = new int[10][]; allocates an array on the heap and assigns a reference to that object to someArray .

When the method GetQuiz() finishes executing, the only thing "destroyed" is someArray , which is simply the reference to the array. 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.

I think you might find the information in this thread helpful: Stack and Heap memory in Java .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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