Questions about arrays and reference variables and objects in Java

Asked 2 years ago, Updated 2 years ago, 92 views

public class HeapQuiz {

int id = 0;

 public static void main(String []args) {

 int x =0;
 HeapQuiz [] hq = new HeapQuiz[5];
 while(x <3) {
     hq[x] = new HeapQuiz();
     hq[x].id =x;
     x = x +1;

 }
 hq[3] = hq[1];
 hq[4] = hq[1];
 hq[3] = null;
 hq[4] = hq[0];
 hq[0] = hq[3];
 hq[3] = hq[2];
 hq[2] = hq[0];

 System.out.println(hq[3]);   }

}

In situations where the above code is present,

There is a problem to connect reference variable and HeapQuiz object.

The reference variable is

hq[0]

hq[1]

hq[2]

hq[3]

hq[4]

and

For HeapQuiz

id = 0

id = 1

id =2

There is.

I'm asking because I don't know how to connect the two.

I wonder why you gave the condition int id = 0;.

Masters, please help me

array object reference-variable

2022-09-22 19:05

1 Answers

HeapQuiz[] at hq

HeapQuiz objects created inside the while statement are defined as follows.

We'll go with H0, H1, and H2.

[H0] [H1] [H2] [*] [*]

After you go around the while door, you'll be in the same condition as above. (*) means null.)

The hq array for each code looks like above. For the last line, hq[3], an exception will occur because it is null.

int id = 0; as a variable to store the id for the HeapQuiz object I think it's a member variable.


2022-09-22 19:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.