Rus9Mus9 Rus9Mus9 - 11 months ago 43
Java Question

Why does the "int id" is changing

I just have started Learning Java reading a book HeadFirst (2nd edition). And i really wonder what is the sense of exercise on 65 page (class HeapQuiz).

Here's a code

class HeapQuiz {
int id = 0;
public statiс 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];

The Question is why does "id" change? It's declared 0, but what is the reason of this changing?
Why is it 1 and 2? Does the program should output like this hq[x].0, hq[x].0 and so on? And okay, this way what is the essential of this task? Thanks in advance! :)

Answer Source
hq[x].id = x;

This line keeps change your id value. It assigns whatever comes in x while in iteration.