Fatso
Fatso

Reputation: 1318

Java Reference Issue

I'm very new to Java, so I'm sorry if this is a bit too stupid for you. So, I have a class called Construct that has an instance variable previousState. I have a setter in that class, with the signature setPreviousState.

Then, in an other class I set the previous State of a Construct object with this code :

    ArrayList<Construct> sequence = new ArrayList<Construct>();
    do {
        Construct minimum = priorityQueue.delMin();
        for (Construct neighbor : minimum.neighbors()) {
            neighbor.setPreviousState(minimum);
            priorityQueue.insert(neighbor);
        }
        System.out.println(minimum);
        if (minimum.isGoalState()) {

            // Construct sequence backwards and return it
            sequence.add(minimum);
            while(minimum.previousState() != null) {
                sequence.add(0, minimum.previousState());
            }
            return sequence;
        }
    } while (true);

But while(minimum.previousState() != null) is an infinite loop because previousState() always references the same object. Why?

Upvotes: 0

Views: 81

Answers (2)

JB Nizet
JB Nizet

Reputation: 692231

Just because you never change what the minimum variable points to in the loop. So you're checking again and again that the same minimum's previousState is not null, without ever changing the minimum's value nor the minimum's previousState.

Upvotes: 1

amit
amit

Reputation: 178521

You never change the value of minimum in this loop, and it seems that the value of minimum.previousState() is also constant for each object [no side affects to method previousState()], you might want to add minimum = minimum.previousState(); to your while loop:

while(minimum.previousState() != null) {
   sequence.add(0, minimum.previousState());
   minimum = minimum.previousState();
}

Upvotes: 2

Related Questions